#239 – The this Reference

In C#, the this keyword refers to the current instance of a class–i.e. the specific instance that an instance method was invoked on.

For example, assume that we have a Dog class and kirby is an instance of this class and that we invoke the Dog.PrintNameAndAge method as follows:

    kirby.PrintNameAndAge();

If the this keyword appears in the implementation of the PrintNameAndAge method, it refers to the kirby object.

        public void PrintNameAndAge()
        {
            Console.WriteLine("{0} is {1} yrs old", Name, Age);

            // Assume we have a static TrackDogInfo method in
            //   a DogUtilities class--and that it accepts a
            //   parameter that is a reference to a Dog object.
            DogUtilities.TrackDogInfo(this);
        }

We passed a reference to the kirby instance to the TrackDogInfo method.  It will therefore have access to all of the instance data in the kirby object, as stored in the object’s fields.

Advertisements