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,
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
Invoke Constructor of the same class using this
thisWhile working with constructor overloading, we might have to invoke one constructor from another constructor. In this case, we can use this keyword. For example,
In the above example, we have used : followed by this keyword to call one constructor from another.
Last updated