Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper use of keyword 'this' in private class members? [duplicate]

Tags:

c#

.net

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.

like image 426
Alex Baranosky Avatar asked Nov 30 '22 07:11

Alex Baranosky


1 Answers

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);
like image 94
Marc Gravell Avatar answered Dec 05 '22 05:12

Marc Gravell