4

When should the keyword 'this' be used within C# class definitions?

Is it standard to use the form "this.Method()" from within class? Or to just use "Method()"? I have seen both, and usually go with the second choice, but I would like to learn more about this subject.

Alex Baranosky
  • 48,865
  • 44
  • 102
  • 150

4 Answers4

15

Most of the time it is redundant and can be omitted; a few exceptions:

  • to call a chained constructor: Foo() : this("bar") {}
  • to disambiguate between a local argument/variable and a field: this.foo = foo; etc
  • to call an extension method on the current instance: this.SomeMethod(); (where defined as public static SomeMethod(this Foo foo) {...})
  • to pass a reference to the current instance to an external method: Helper.DoSomething(this);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

this is mainly used to explicitly use a class member when the name alone would be ambiguous, as in this example:

public class FooBar
{
    private string Foo;
    private string Bar;

    public void DoWhatever(string Foo, string Bar)
    {
        // use *this* to indicate your class members
        this.Foo = Foo;
        this.Bar = Bar;
    }

    public void DoSomethingElse()
    {
        // Not ambiguity, no need to use *this* to indicate class members
        Debug.WriteLine(Foo + Bar);
    }
}

Aside from that, some people prefer to prefix internal method calls (`this.Method()´) because it makes it more obvious that you are not calling any external method, but I don't find it important.

It definitely has no effect on the resulting program being more or less efficient.

Treb
  • 19,903
  • 7
  • 54
  • 87
2

I use 'this' when it becomes ambigious what your refering to, it having a local variable with the same/similar name to a class variable/method.

But its really a personal preference thing, just use what you feel is best.

Sam
  • 5,416
  • 7
  • 47
  • 49
  • I was tending towards not using 'this' 95% of the time. But then I started to wonder if I was missing something. I can always be sure to clarify things here on SO. – Alex Baranosky Jan 26 '09 at 10:27
1

always... just my 2 cents