In C#, this keyword is used to avoid scope ambiguity. In any C# class this keyword is used to specify the current class instance. For example we have Employee class and it has method SetEmpId() as shown below.
public class Employee
{
public int iEmpId;
public void SetEmpId(int iEmpId)
{
iEmpId = iEmpId;
}
}
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee();
obj.SetEmpId(10);
Console.WriteLine(obj.iEmpId.ToString());
Console.ReadLine();
}
}
As shown above we are trying to set the Employee class variable iEmpid variable through SetEmpId() method. But incoming parameter of SetEmpId() method also has same name iEmpId, so it is assigning the input parameter to itself instead of assigning to class level variable iEmpId. The output display as "0" because of this. This is called scope ambiguity, to avoid this use this keyword as shown below.
public class Employee
{
public int iEmpId;
public void SetEmpId(int iEmpId)
{
this.iEmpId = iEmpId;
}
}
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee();
obj.SetEmpId(10);
Console.WriteLine(obj.iEmpId.ToString());
Console.ReadLine();
}
}
As shown above we are setting the input parameter to the class level variable by using this keyword. Now the output displays correctly "10".
Not only for scope ambiguity, even in unambiguous situations also this keyword is used to enable the intellisense in Visual Studio IDE.
Constructor Chaining using this Keyword:
As we know we can have multiple constructors in any class, we can chain these constructors using this keyword as shown below.
public class Employee
{
public int iId;
public string sName;
public Employee()
: this(0, string.Empty)
{
}
public Employee(int iEmpId)
: this(iEmpId, string.Empty)
{
}
public Employee(string sEmpName)
: this(0, sEmpName)
{
}
public Employee(int iEmpId, string sEmpName)
{
iId = iEmpId;
sName = sEmpName;
}
}
As shown above we have four constructors, all first three constructors are calling last constructors using this keyword. Constructor flow also whenever you are calling first constructor calls last constructor which is master constructor, it is same for all three constructors.