This keyword


In this article we are going to discuss about this keyword with examples in C#.

This Keyword

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.

Uses of this Keyword Real Applications

  1. To Reference Instance Members

    • Differentiating between instance members and parameters with the same name.
    • Accessing instance members within the class.

  2. Constructor Chaining

    • Invoking one constructor from another within the same class.
  3. Extension Methods

    • Specifying the type that the extension method operates on.

Example Scenarios

1. Differentiating Between Instance Members and Parameters

When instance variables have the same names as method parameters, this can be used to avoid ambiguity.

This Keyword in C#

In this example, this.firstName and this.lastName refer to the instance variables, while firstName and lastName refer to the parameters of the constructor.

2. Constructor Chaining

Using this to call another constructor in the same class.

This Keyword in C#

In this example, the first constructor calls the second constructor using this.

3. Extension Methods

When defining extension methods, the this keyword is used to specify the type that the method extends.

This Keyword in C#

In this example, the IsNullOrEmpty method extends the string type.


Prev Next