C# this Keyword


You probably won’t need to use the this keyword very often, partly because it can only be used in certain circumstances. However it can be used with indexers and extension methods. The this keyword can be used only in the blocks of the following class members:

  • Instance constructors
  • Instance methods (as seen below in the example code)
  • Instance accessors of properties and indexers (indexers are covered in the next section)

The this keyword, used in a class, is a reference to the current instance. The book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress has an example of using the this keyword. This is only an example and this style of coding is not recommended since you shouldn’t use the same name for your member variable and for your parameter name.

Clearly, since static members are not part of an instance, you cannot use the this keyword inside the code of any static function member.


namespace thisKeyword
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            Console.WriteLine(mc.ReturnMaxSum(12)); // OUTPUT: 12
            Console.WriteLine(mc.ReturnMaxSum(7));  // OUTPUT: 10
        }
    }
    class MyClass
    {
        int Var1 = 10;  // a field
        //  Below, both are called “Var1” (not recommended)
        //  The method compares the values of the parameter 
        //  and the field and returns the greater value.
        public int ReturnMaxSum(int Var1)  // method takes a single int parameter
        {
            // Parameter is Var1
            // Field is this.Var1
            return Var1 > this.Var1
            ? Var1 // Parameter
            : this.Var1; // Field
        }
    }
}