Is always prefixing (auto)properties with the this-keyword considered a good practice?
Asked Answered
N

4

7

Ever since I found out about auto properties, I try to use them everywhere. Before there would always be a private member for every property I had that I would use inside the class. Now this is replaced by the auto property. I use the property inside my class in ways I normally would use a normal member field. The problem is that the property starts with a capitol, which makes it look a bit weird imho when using it in this manner. I didn't mind that properties start with a capitol before because they would always be behind a "dot". Now I have found myself prefixing all the properties I use internally with this., to sooth my feeling.

My dilemma is that before I was always a bit against prefixing all usage of internal members with this., unless "necessary" (like in a setter or constructor). So I am kind of looking for a second opinion on this. Is there a standard good way to do this? Should I just stop complaining (I have the tendency to be a "ant humper" (Dutch expression))?

Before:

class Foo
{
    private Bar bar;
    public Bar Bar { get { return bar; } }

    public Foo(Bar bar)
    {
        this.bar = bar;
    }

    public void DoStuff()
    {
        if(bar != null)
        {
            bar.DoMethod();
        }
    }
}

After:

class Foo
{
    public Bar Bar {get; private set;}

    public Foo(Bar bar)
    {
        this.Bar = bar;
        // or
        Bar = bar;
    }

    public void DoStuff()
    {
        if(this.Bar != null)
        {
            this.Bar.DoMethod();
        }
        // or
        if(Bar != null)
        {
            Bar.DoMethod();
        }
    }
}

Update

It seems that opinions vary, although more people are in favor of prefixing with this.. Before the auto properties I was always pretty much against prefixing with this. instead of in constructors and in setters (as I mentioned before). But now I just don't know anymore.

Additional note: The fact that it is also common to name the property the same as the class (public Bar Bar { get; private set; }) also makes me tend towards prefixing. Every time I type Bar.DoMethod(), I feel like it looks like a static method. Even though VS would color Bar if it was a static method and you cannot have a static and instance method with the same signature. When it is colored it is clear that it is a static method, but when it is not colored it is not 100% clear that it is not a static method. You could for example just be missing a using statement, but also just because I am not used to having to link the not being colored to whether it's a static call or not. Before I'd instantly see it by the capitalization of the first letter in case of a member or by the "dot" in case of a property (E.g. the "dot" after foo in (Foo)foo.Bar.DoMethod()).

(Difficult to choose an "Accepted answer" at the moment)

Nicolais answered 18/1, 2010 at 13:1 Comment(5)
Interesting, how do you manage to give a property the same name as the class? This is illegal syntax and will throw "member names cannot be the same as their enclosing type" error when compiling.Garnet
@Abel, no it doesn't :) StackOverflow colors the second Bar wrong, but VS accepts it. I have already read a bunch of questions about if that is good practice or not, from which I concluded that it was. #525819 #1096144 #2024493Nicolais
I see the problem. That error would arise when I would name the property Foo. Foo is the enclosing type not Bar.Nicolais
Ah: you meant using the typename of the returned type as the name of the property, not necessarily being the enclosing type. Yes, that's fine of course.Garnet
Thanks for the title edit, I had a bit of a problem formulating the question in one sentence without it becoming a sentence fit for an episode of "Zero Punctuation".Nicolais
G
6

Yes, there is a "standard way to do this": the capital letter and the this-prefix are considered good coding practice. If you use some tool to test your code for coding guidelines like ReSharper or Microsoft's own StyleCop, it will warn you if not using the this-reference, or if you don't start your properties with a capital.

Your properties are publicly visible. Any public property, field or method should start with a capital.

Any property, field or method that you call inside your own class that is part of that class should be prefixed with the this-reference for ease-of-reading.

Update: of course, opinions vary. I like hitting this. and then, after the dot, seeing only the members, instead of seeing all keywords when just hitting ctrl-space without any prefix. This helps me. But, in the end (quote from here):

Whatever your opinion, the important thing is that all people closely collaborating on a project use the same formatting standards, irrespective of what those standards are.

More references:
Microsoft on using a capital letter in almost any name and in properties specifically.
More guidelines here.

Garnet answered 18/1, 2010 at 13:7 Comment(4)
Heh, funny. DevExpress CodeRush does the exact opposite - it warns you about unnecessary usage of "this". Although I ignore it and use it anyways - I like this guideline as well.Stapleton
As far as I know, R# does the same as DevExpress by default. Annoys me, so I probably have to switch it around ;-)Rebbecarebbecca
Thanks for your answer. I think this one is the most complete. I have been convinced to use this. :)Nicolais
@Erik and others: you can use StyleCop For Resharper if you want to be sure to follow MS's coding guidelines, which includes the this-enforcing-rule: codeplex.com/StyleCopForReSharperGarnet
B
6

I strongly recommend to use 'this.' where possible. Framework Design Guidelines recommends this practice. It lets you know the scope from readability point of view and helps you avoid silly mistakes which compiler may report at compile time.

Bovill answered 18/1, 2010 at 13:7 Comment(6)
Personally I hate it when someone uses needless disambiguation prefixes.Tecu
Personally, I hated it too, but once I got used to it, it doesn't work as "prefix" it works as a guide: it makes code more readable. And it is much less contrived then the old-style Hungarian Notation prefixes like psz_ etc.Garnet
@abel: I agree, those are even worse :)Tecu
I see one major advantage for using them: if you later on introduce a local variable with the same name, you won't break your code. ;)Stapleton
Could you point me at where in The Book this recommendation is? From what I can see (I have the first edition, in paper), Appendix A (the part that talks about coding conventions as opposed to public interface design) has nothing on thisSearby
I don't know where in that book, but in this book, it's on page 23: scribd.com/doc/23955617/c-code-style, arguing it's clearer to differentiate between variables in the method and fields (or methods/properties) in the class level.Garnet
M
2

And I strongly recommend never using this as it only ever reduces clarity. If you actually find yourself in an instance where you need this to avoid collisions I would recommend renaming one of the fields/properties/variables.

The only place I find it acceptable is if it's part of a publicly exposed API where renaming would cause a breaking change.

Marilou answered 18/1, 2010 at 13:11 Comment(9)
How can it cause a breaking change from a public API point of view?Tecu
Prefixing gives the advantage that if you later introduce a parameter/local variable with the same name, you won't break your code. And it doesn't ever reduce clarity or readability. :)Stapleton
@Lepidus If you have a public field/property with the same name as a paramter already. @Vilx I disagree, having pointless words in your code doesn't help anything. It's like putting a comment above a for loop that says //for loop, if you actually use this for when you need it even if it makes it unambiguous for the compiler it's still very ambiguous.Marilou
@Chris, do you also recommend against prefixing with "this." in the case of the constructor of Foo in the "before" code (E.g. by renaming one of the variables)?Nicolais
@Chris: I agree with your example of the comment to the for loop. But this is something different. If you look at the for loop, you see what is does. If you look at Bar, you don't know whether it is a member or not.Squint
+1 for an opposing view, -1 because I strongly disagree with "it ever reduces clarity". I find myself often hitting F12 or scroll around to find where a certain property or method is declared. Using this. makes it very clear what the intend is and saves me many lookups. It doesn't reduce clarity (unless you use it unconsistently), it improves clarity. StyleCop demands it and Microsoft demands it (internally), I assume for a reason: social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/…Garnet
I would say that not using this reduces clarity. I guess this is one of those things where opinions are always be polarised!Dishevel
"never" is too strong a word here. fine if you don't like it in general use, but saying it never has a use is inaccurate.Extravagate
@Matthijis yes, I would recommend renaming the variables, I think it is poor naming to ever leave 2 conflicting variables so you need to use this. I use the R# standard naming template, private members _, lower case first letter parameters and title cased public members. CLS compliant and never will need a this. modifier.Marilou
T
1

In the first example, the bar parameter lexically shadows bar field from the instance. So you have to use this for disambiguation.

In the 2nd example you have no such ambiguity, and hence does not need a disambiguation (ie this). You can however still prefix it, if that is your cup of tea. :)

Tecu answered 18/1, 2010 at 13:7 Comment(3)
Prefixing gives the advantage that if you later introduce a parameter/local variable with the same name, you won't break your code.Stapleton
@ leppie, Well I know what the this means and what it does. My problem is that my cup of tea has gotten cold and I need a new one. But I find it hard to choose. So I want to know if one cup comes more highly recommended than the others.Nicolais
@Matthijs: I dont recommend it. Why would you do something that is not necessary and adds verbosity to your code, and make it possibly harder to read?Tecu

© 2022 - 2024 — McMap. All rights reserved.