This .NET C# blog post will explain when to use the “this” keyword in a C# application and its purpose.
The keyword “this” in .NET distinguishes between a variable (a field) and a parameter with the same name. When using “this”, it will prefix the variable, not the parameter.
Code Example
In the following code, I have an instance variable (called x) and a constructor parameter with the same name (x). I will use the “this” keyword to refer to the instance variable.
public class MyClass
{
private int x;
public MyClass(int x)
{
this.x= value; // 'this' refers to the instance variable x
}
}
We can also use the “this” keyword to access a Method or a Property, as shown in the following example.
public class MyClass
{
private int x;
public void SetValue(int y)
{
this.x= y; // 'this' refers to the x instance variable
}
public int GetValue()
{
return this.x; // Retu
}
}
Closing
Using the “this” keyword prevents writing ambiguous statements where the compiler doesn’t know how to distinguish between a variable and a parameter with the same name.
Leave a Reply