C# this Keyword
In C#, this
keyword refers to the current instance of a class. For example,
Here are some of the major uses of this
keyword in C#.
C# this with Same Name Variables
We cannot declare two or more variables with the same name inside a scope (class or method). However, instance variables and parameters may have the same name. For example,
In the above program, the instance variable and the parameter have the same name: num
. We have passed 4 as a value to the constructor.
However, we are getting 0 as an output. This is because the C# gets confused because the names of the instance variable and the parameter are the same.
We can solve this issue by using this.
Example: this with Same Name Variables
Invoke Constructor of the same class using this
this
While working with constructor overloading, we might have to invoke one constructor from another constructor. In this case, we can use this
keyword. For example,
In the above example, we have used :
followed by this
keyword to call one constructor from another.
Note: Calling one constructor from another constructor is known as constructor chaining.
Last updated