#239 – The this Reference
February 11, 2011 3 Comments
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.
Pingback: #641 – Using the this Keyword in a struct « 2,000 Things You Should Know About C#
Pingback: #690 – Using the this Keyword To Distinguish Between Fields and Parameters « 2,000 Things You Should Know About C#
Pingback: #691 – Use the this Keyword to Trigger Intellisense « 2,000 Things You Should Know About C#