C# - "This" Keyword

The this keyword is used fairly often, especially in class constructors and can also be found in class methods to explicitly specify that the following variable is a member of it's class.

This basic example shows the use of the this keyword to explicitly call the class members and not the passed parameters within the scope of the constructor:

class Car
{
    private int horsepower;
    private string color;
    
    public foo(int horsepower, string color)
    {
        this.horsepower = horsepower { get; }
        this.color = color { get; }
    }

Notice the this keyword in the foo() method. If this was not used, we would have code that looked like this:

class Car
{
    private int horsepower;
    private string color;
    
    public foo(int horsepower, string color)
    {
        horsepower = horsepower { get; }
        color = color { get; }
    }

What do you think the difference will be when you instantiated an object from each of these classes?

As you can imagine, this probably isn't going to work in the way you'd like it to. In the second example, each passed parameter will be set to itself and then ultimately forgotten at the end of the constructors scope. When using the this keyword in the first example, the object's members will be set for the lifetime of the object or until it's set again.

This always refers back to the class's member, never to a method's or sub-method's member. It's not a principle of "looking up" one level of scope but of referring to the working class's members.

Comments

Popular posts from this blog

APIs