C# this Keyword

In C#, "this" is a keyword that refers to the current instance of a class. It is used to refer to members of the current instance of a class, and can be useful in avoiding naming conflicts between class members and parameters of the constructor or method.

Using "this" to Access Members of the Current Instance

The "this" keyword can be used to refer to members of the current instance of a class. For example, consider the following class:

1class MyClass 2{ 3 private int myInt; 4 5 public MyClass(int myInt) 6 { 7 this.myInt = myInt; 8 } 9}

In the constructor for MyClass, "this" is used to refer to the current instance of the class, and the value of the "myInt" parameter is assigned to the "myInt" field of the class.

Using "this" to Avoid Naming Conflicts

The "this" keyword can also be useful in avoiding naming conflicts between class members and parameters of the constructor or method. For example, consider the following class:

1class MyClass 2{ 3 private int myInt; 4 5 public MyClass(int myInt) 6 { 7 this.myInt = myInt; 8 } 9 10 public void DoSomething(int myInt) 11 { 12 this.myInt = myInt; 13 } 14}

In this example, "this" is used to refer to the "myInt" field of the class, in order to avoid naming conflicts with the "myInt" parameter of the "DoSomething" method.