If I am accessing a member field, property, or method, I'm never sure when I should prepend it with 'this'.
I am not asking about cases where it is required, like in the case where a local variable has the same name. I am talking about cases where the meaning is exactly the same. Which is more readable? Are there any standards, best practices, or rules of thumb I should be following? Should it just be consistent throughout a class, or an entire code base?
I disagree with StyleCop on this one, and I'm not even sure that StyleCop's opinion should be interpreted as an official Microsoft guideline anyway. It was an internal tool used at Microsoft but not all teams use it, and not all teams use all the rules.
Adding this
everywhere is not necessary and often just adds clutter. It does not improve performance and I'm not convinced that adding this
all over the code improves readability either.
You might hear arguments that it makes it more clear where the variable is defined, but I would argue that if your class/method is so long and complicated that it is difficult to work out where something is declared then you probably should refactor it anyway. If you use the single responsibility rule and have short functions it should be obvious whether a variable is a member, a function parameter or a local variable.
As you point out, sometimes it is necessary. For example in the constructor if you want to set a private member with the same name as the parameter.
public class Foo
{
private Bar bar;
public Foo(Bar bar)
{
this.bar = bar;
}
}
I recommend using Microsoft's guidelines, as verified by StyleCop: http://blogs.msdn.com/sourceanalysis/
The general rule is, prepend members with "this." when they are defined in the class, unless they are static, in which case you cannot.
Here is the rule directly from StyleCop:
SA1101: The call to {method or property name} must begin with the
'this.' prefix to indicate that the item is a member of the class.
I would say avoid as much as possible, it saves you some(in fact a lot of) typing.
I would depend on Visual Studio more to help me to find where what belongs(never forget F12). I don't use notepad to read my cs files :P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With