Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good rule for when to prepend members with 'this' (C#)?

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?

like image 447
noctonura Avatar asked Apr 28 '10 18:04

noctonura


3 Answers

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;
    }
}
like image 196
Mark Byers Avatar answered Nov 10 '22 00:11

Mark Byers


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.
like image 26
Kevin Albrecht Avatar answered Nov 09 '22 23:11

Kevin Albrecht


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

like image 28
Numan Avatar answered Nov 09 '22 23:11

Numan