"this" Keyword in C#

Mannan Ul Haq
0
In C#, `this` is a keyword that refers to the current instance of the class. It's typically used within a class to refer to the instance that's currently being worked with.

Here are a few common scenarios where `this` keyword is used:

1. To distinguish between class fields and method parameters, when they have the same names:

class Employee
{
    private string name;

    public Employee(string name)
    {
        this.name = name; // 'this' refers to the class field, 'name' is the method parameter.
    }
}


2. To refer to the current instance of the class within an instance method or property:

class Employee
{
    public string name;

    public void IntroduceYourself()
    {
        Console.WriteLine("Hi, my name is " + this.name);
    }
}


In all these cases, `this` refers to the object that the method is being called on. 

It's worth noting that usage of the `this` keyword is not always necessary. It's often used for clarity and to avoid naming conflicts. Without `this`, if a method parameter has the same name as a class field, the method parameter would take precedence. This could lead to unexpected behavior if you're not careful, so `this` can be used to make the code more understandable.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !