C# this Keyword

In C#, this keyword refers to the current instance of a class. For example,

using System;
class Car
{
    string brand;
    public Car(string brand)
    {
      this.brand = brand;
    }
    public string ShowBrand()
    {
        return this.brand;
    }
}

class Program
{
    static void Main()
    {
        Car car1 = new Car("Honda");
        Console.WriteLine(car1.ShowBrand());
        Console.ReadLine();
    }
}

Here are some of the major uses of this keyword in C#.

C# this with Same Name Variables

We cannot declare two or more variables with the same name inside a scope (class or method). However, instance variables and parameters may have the same name. For example,

using System;
 
namespace ThisKeyword {
  class Test {

    int num;
    Test(int num) {

      num = num;
    }

    static void Main(string[] args) {

      Test t1 = new Test(4);
      Console.WriteLine("value of num: " + t1.num);
      Console.ReadLine();
    }
  }
}

In the above program, the instance variable and the parameter have the same name: num. We have passed 4 as a value to the constructor.

However, we are getting 0 as an output. This is because the C# gets confused because the names of the instance variable and the parameter are the same.

We can solve this issue by using this.

Example: this with Same Name Variables

using System;
class Car
{
    string brand;
    public Car(string brand)
    {
        //wrong, will not work!
        brand = brand;
    }
    public string ShowBrand()
    {
        //no problem
        return brand;
    }
}

class Program
{
    static void Main()
    {
        Car car1 = new Car("Honda");
        Console.WriteLine(car1.ShowBrand());
        Console.ReadLine();
    }
}

Invoke Constructor of the same class using this

While working with constructor overloading, we might have to invoke one constructor from another constructor. In this case, we can use this keyword. For example,

using System;
class Car
{
    string brand;
    int price;
    public Car(string brand)
    {
        this.brand = brand;
    }

    public Car(string brand, int price):this(brand)
    {
        this.price= price;
    }

    public void ShowBrandPrice()
    {
       Console.WriteLine(brand+ " " + price);   
    }
}

class Program
{
    static void Main()
    {
        Car car1 = new Car("Honda");
        car1.ShowBrandPrice();

        Car car2 = new Car("Toyota",200);
        car2.ShowBrandPrice();

        Console.ReadLine();
    }
}

In the above example, we have used : followed by this keyword to call one constructor from another.

Note: Calling one constructor from another constructor is known as constructor chaining.

Last updated