#691 – Use the this Keyword to Trigger Intellisense

Another use of the this keyword, which refers to the current instance of a class, is to trigger Intellisense in Visual Studio so that you can  see a list of members in the class.

For example, let’s say that you’re writing some code for the Bark method in a Dog class.  You want to call another method in the Dog class, but you can’t remember its name.  You can just type this and a period (.).  After typing the period, an Intellisense window will pop up to show you the members in the Dog class.

You can then select the method that you want to call and Intellisense will remind you of what parameters are required.

Advertisement

#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.