user4691433
user4691433

Reputation:

Does `this` inside a class method refer to the called or default instance?

In VBA, I constantly passed class instances as parameters to their own methods if I was going to be modifying their property values. To give an extremely simplified C# example:

class WhateverClass
{
    public void DoSomething(WhateverClass whateverClass)
    {
        whateverClass.WhateverProperty = "Hello"
    }
}

In C#, can I avoid needing to pass called class instances as parameters by using this, like so? Or will this refer to the default class instance?

class WhateverClass
{
    public void DoSomething()
    {
        this.WhateverProperty = "Hello"
    }
}

Upvotes: 2

Views: 96

Answers (2)

user4691433
user4691433

Reputation:

this refers to the called class instance.

I made the following test app to check:

class Program
{
    static void Main()
    {
        var class1 = new Class1();
        class1.Setup();

        Console.Write(class1.Property1);
        Console.ReadKey();
    }
}


class Class1
{
    public string Property1 { get; set;}

    public Class1 ()
    {
        this.Property1 = "Overwrite me";
    }


    public void Setup()
    {
        this.Property1 = "Successfully overwritten";
    }
}

The output of this was "Successfully overwritten"

Upvotes: 3

Christopher
Christopher

Reputation: 9824

It refers to the instance, the method is called on.

DoSomething is non-static, so it has to be called on a instance.

A interesting case is "this" as used in extension methods. Extension methods are little more then syntactic sugar for static functions, which have to be called on a class instance. In that case, it is annotating the 1st Parameter, which will automagically be the instance it is called upon.

Upvotes: 1

Related Questions