This article will provide detailed information about the “this” keyword in C# with an example.
What is this Keyword in C#?
In the C# programming language, the “this” keyword is a pointer to the reference of a class itself. It helps to access the members of the current object, such as the constructor, and methods. The word “this” is frequently used to differentiate among instance members with an identical name and local variables or arguments. It improves readability and comprehension of the code.
Example: How to Refer to the Present Element of Class Using “this” Keyword?
To refer the present member of a class in C# using the “this” keyword, first, use the “using System” to recognize code elements and make globally unique types. It is used to acquire the System namespace, allowing users access to the.NET framework’s functionalities:
Next, utilize the “this” keyword within the “my_Class” method to refer to the current instance. Then, declare the “SetTotalValue()” function that takes only one argument and assigns the integer type value as a parameter to the “amount” field of the current instance by using the “this.amount”. As in parallel, the “GetTotalValue()” method is specified to return the value of the “amount” using return “this. amount”:
{
private int amount;
public void SetTotalValue(int value)
{
this.amount = value;
}
public int GetTotalValue()
{
return this.amount;
}
}
After that, the “Program” is defined and the static void “Main()” method is used inside the class. Then, the object of the “my_Class” is called with the “SetTotalValue()” method that takes the integer value “40” as an argument. Lastly, call the “Console.WriterLine()” to display the total value on the terminal:
{
static void Main()
{
my_Class my_Object = new my_Class();
my_Object.SetTotalValue(40);
int total_Value = my_Object.GetTotalValue();
Console.WriteLine("Total value is: " + total_Value);
}
}
As you can see, the resultant value of the above-executed code is shown in the provided output:
Note: The “this” keyword in C# improves code readability, permits method chaining, and extensions of existing classes.
That’s it! We have illustrated the usage of the “this” keyword in C#.
Conclusion
In C++, Keyword “this” is extensively used as a pointer referring to an active member of a class. It provides a reference to its member parameters and member functions. When separating among local variables and members of a class. In this tutorial, we have demonstrated the detail of the “this” keyword in C#.