#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #239 – The this Reference

  1. Pingback: #641 – Using the this Keyword in a struct « 2,000 Things You Should Know About C#

  2. Pingback: #690 – Using the this Keyword To Distinguish Between Fields and Parameters « 2,000 Things You Should Know About C#

  3. Pingback: #691 – Use the this Keyword to Trigger Intellisense « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: