tags:

views:

244

answers:

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.

+1  A: 

always... just my 2 cents

Andreas Niedermair
+12  A: 

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
+2  A: 

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
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
+2  A: 

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