When NOT TO USE 'this' keyword?
My rule of thumb: Never use 'this' when it is redundant. In this case, 'this' is redundant, so I would avoid it. A tool like ReSharper is very good at telling you when this is the case.
this
is almost always optional and does not need to be specified. If you want to be explicit that you are referring to a member, then use this
. If you have a naming convention (such as naming all member fields something like _foo
), then you really don't need to refer to them like this._foo
.
It's a matter of personal taste (no performance penalty), but I find having the explicit this
is harder to maintain and adds little value if you have a solid naming convention. Some people will only use this
when calling a member method, e.g. this.Foo(_bar)
instead of Foo(_bar)
, but again, I don't personally believe it adds much.
If you're working with existing code, follow the convention there, otherwise, pick whichever makes you the most productive and effective.
I always use this.
to make it clear that I am referring to a class member, not a local variable.
I always use this
. I use the same naming convention for local variables and private fields and it makes the code much easier to read because it becomes obvious if the used identifier is a field or local variable.
Further it prevents the introduction of bugs by adding a new local variable that hides a field.
internal sealed class Foo
{
private Int32 bar = 42;
private void Bar()
{
// Uncommenting the following line will change the
// semantics of the method and probably introduce
// a bug.
//var bar = 123;
Console.WriteLine(bar);
// This statement will not be affected.
Console.WriteLine(this.bar);
}
}
This can be avoided by using different naming conventions for fields and local variables but I really dislike underscore prefixed names. The first character of a word is very important for its readability and an underscore is one of the worst possible choices.