#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

#690 – Using the this Keyword To Distinguish Between Fields and Parameters

The this keyword refers to the current instance of a particular class.

One common use for the this keyword is to qualify a variable name, indicating that the name in question is a member of the class.

In the example below, we have two properties in a class that have the same name as parameters passed in to a constructor.  We want to assign the value of the parameters to the properties.  But the compiler doesn’t know which name or age we mean in the assignment statements.  (Notice the warning).

We can clear up the confusion by prefixing the property names with the this keyword.

        public string name { get; set; }
        public int age { get; set; }

        public Dog(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

You could also use a naming convention to avoid the confusion, e.g. make the property names capitalized.

#642 – Reassigning the this Pointer in a struct

The this keyword in a struct refers to the current instance of the object represented by the struct.  

You can actually assign a new value to the this keyword, provided that the new value is an instance of the same struct.

    public struct BoxSize
    {
        public double x;
        public double y;
        public double z;

        public BoxSize(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public void CopyFrom(BoxSize newBoxSize)
        {
            // Overwrite existing BoxSize with a new one
            //   by assigning new value to this keyword
            this = newBoxSize;
        }

        public void PrintBoxSize()
        {
            Console.WriteLine(string.Format("X={0}, Y={1}, Z={2}", x, y, z));
        }
    }
        static void Main()
        {
            BoxSize myBox = new BoxSize(5, 2, 3);
            myBox.PrintBoxSize();

            myBox.CopyFrom(new BoxSize(10, 20, 30));
            myBox.PrintBoxSize();
        }

#641 – Using the this Keyword in a struct

In a class, the this keyword refers to the current instance of a class, or the instance that a particular method was invoked on.

You can also use the this keyword in a struct and it will refer to the current instance of the struct.

In the example below, the this keyword is used to refer to the fields of the current instance of the struct, to distinguish them from the input parameters that have the same name.

    public struct BoxSize
    {
        public double x;
        public double y;
        public double z;

        public bool HasBiggerVolume(double x, double y, double z)
        {
            if ((this.x * this.y * this.z) > (x * y * z))
                return true;
            else
                return false;
        }
    }

#362 – Defining an Indexer

An indexer is a class member that allows client code to index into an instance of class using an integer-based (0..n-1) index.  The indexer allows an instance of a class to behave like an array.

Assume that we define a Logger class that stores a series of log messages in an internal collection:

    public class Logger
    {
        private List<LogMessage> messages = new List<LogMessage>();

        public void LogAMessage(LogMessage msg)
        {
            messages.Add(msg);
        }

    }

We define an indexer by defining a member that looks like a property, but uses the this keyword.

        public LogMessage this[int i]
        {
            get
            {
                return messages[i];
            }
        }

The indexer allows us to write code that indexes into an instance of the class:

            Logger log = new Logger();

            log.LogAMessage(new LogMessage("This happened", 5));
            log.LogAMessage(new LogMessage("Something else happened", -1));

            LogMessage lm = log[1];   // returns 2nd element

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