In this article we are going to discuss about this keyword with examples in C#.
The this keyword in C# is a reference to the current instance of the class or struct within which it is used. It is primarily used to differentiate between instance members (fields, properties, methods) and parameters or local variables with the same name. Additionally, it is used in extension methods to specify the type that the method extends.
To Reference Instance Members
Constructor Chaining
Extension Methods
When instance variables have the same names as method parameters, this can be used to avoid ambiguity.
In this example, this.firstName and this.lastName refer to the instance variables, while firstName and lastName refer to the parameters of the constructor.
Using this to call another constructor in the same class.
In this example, the first constructor calls the second constructor using this.
When defining extension methods, the this keyword is used to specify the type that the method extends.
In this example, the IsNullOrEmpty method extends the string type.