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)