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

Advertisements