What is this keyword?
In C#, the "this" keyword is a reference to the current instance of the class that is being executed. It is often used within class methods and constructors to refer to the object on which the method is being called.
Here are a few common uses of the "this" keyword in C#:
1.
Accessing Instance Members: When a class has instance variables and methods with the same name as method parameters or local variables, you can use the "this" keyword to refer to the instance variables. This helps disambiguate between the local variable and the instance variable.
class MyClass
{
private int myNumber;
public void SetNumber(int myNumber)
{
this.myNumber = myNumber; // "this" refers to the instance variable
}
}
Here's another example which also illustrates how we can access instance memeber using 'this' keyword:
2. Calling Constructors: In constructors, you can use the "this" keyword to call other constructors in the same class. This is useful for constructor overloading or reusing common initialization logic.
class MyClass
{
private int myNumber;
public MyClass(int number)
{
myNumber = number;
}
public MyClass() : this(0) // Calls the parameterized constructor with a default value
{
}
}
In the example you can also see that how we can other constructor in the same using 'this' keyword:
3. Passing the Current Instance: You can use the "this" keyword to pass the current instance to other methods or objects. This is particularly useful when you want to pass the instance to a method that expects an object of the same class.
class MyClass
{
public void SomeMethod()
{
AnotherClass.DoSomething(this); // Passes the current instance to another method
}
}
In the example below we have also used 'this' keyword to pass the current instance to other method:
In summary, the "this" keyword in C# provides a way to refer to the instance of the class that is currently being operated upon, allowing you to access instance members, disambiguate variables, and perform other operations related to the instance.
Note:The usage of the "this" keyword is applicable to non-static classes; however, employing the "this" keyword within static classes is not permitted.