views:

693

answers:

17

When accessing instance variables or properties of a class from within the class itself, do you prepend them with "this."?

+3  A: 

Anytime I have a method parameter whose name is identical to an instance variable (rarely) I do, to avoid confusion.

Ben S
I think you have to in those cases since the local var/method parameters will shadow the instance var. Agree with you though, helps to avoid confusion.
Arnshea
+2  A: 

No, but then I write a lot of VB ;)

About the only time I'll check this/Me is when I don't remember the exact name of the member or when I need to distinguish it with a function parameter of the same name.

Joel Coehoorn
+2  A: 

Nope! I can certainly see that it might be beneficial, but nothing I work on is sufficiently complex to need another level of clarification.

Andy Mikula
+25  A: 

I only ever use a this. prefix in constructors or setters, primarily in the case where the passed parameters have the same name as the relevant member variables.

Alnitak
Agreed. I only add it to remove ambiguity.
Douglas Tosi
Further agreed. I hate having non-matching names for setters. It doesn't really make sense.
Stefan Kendall
+1It would make equal sense to prepend the namespaces to every object you instantiate.
Nippysaurus
+17  A: 

In C#, I absolutely do. The primary reasons are:

  1. Whether to do it or not is a stylistic issue. In spite of all the fighting that goes on, I don't believe there's an objectively better approach.

  2. My source analysis tool (StyleCop) defaults to requiring this. in front of instance accesses. My first point implies that I shouldn't care much about whether I always do or always don't, and because the default StyleCop setting is to always require it, I take the path of least resistance/greatest consistency and I follow the default setting.

I follow this philosophy for most stylistic issues. I'm a huge fan of not changing default formatting options in an auto-formatting IDE. It just makes everyone's life harder over something that's really just not that important.

Greg D
Default formatting of Resharper removes all the 'this.'. I refrain from using 'this.' except if I can't do without.
Carra
I so do not agree with this answer. Just because it is a default in StyleCop doesn't mean it is right. I think whoever created that rule was probably working on less than 2 hours sleep in 3 days.
Robert Kozak
@robert by saying it's style he means, and I agree, that there's really no universally right behavior in this case. Going with the defaults makes it easier when working at someone else's desk or looking at someone else's code...
Arnshea
Resharper removes them and I agree with Resharper. I agree because I don't feel it's necessary not because Resharper knows best. Don't think it's right because StyleCop says so.
Bobby Cannon
Heh, I thought about referring to it as a religious war, but I didn't want to be inflammatory. Seems the comments have proven it out regardless, though. Arnshea is exactly right. There's no objectively "correct" approach, so just remain consistent within the appropriate domain. I can't believe I have to say that.
Greg D
+2  A: 

We're using ReSharper which manages all of that very well. Most of the time we remove 'this' unless keeping it in a constructor since we typically use constructor parameters with the same name.

Jeff Wain
+3  A: 

I think this practice improves legibility most of the time, so yes.

tehblanx
+8  A: 

It adds clutter. So no.

Beau Martínez
I agree, it is a waste.
Chuck Conway
Totally disagree. If adding this. ads clutter, then your code is probably allready very un-structured.
WebDevHobo
A: 

I do. I got in the habit back when Intellisense in Visual Studio wasn't as clever as it is these days.

I don't find it distracting, I suppose because I write a lot of Python and am used to seeing self everywhere.

Dana
A: 

Only when required to distinguish from parameters, as in a setter or constructor. I consider its use in unnecessary cases to be "codejunk", analogous to Edward Tufte's chartjunk. Noise, instead of signal.

Carl Manaster
A: 

If your instance variable name is same as method argument- it is no longer "simply a reason to clarify". If you don't do prepend- it can lead to defects.

I think that's what Ben S meant- but just wanted to stress- that its not a matter of best practice any more.

I often do- increases clarity. I don't think it adds to clutter- because our brains quickly reads past it, but registers that it is an instance variable

RN
+4  A: 

Absolutely. 'this' avoids the need for any prefixes, such as m_. More importantly, it quickly improves the performance of my code, and this is why:

I've really embraced the Microsoft Cops (FxCop, StyleCop). They've really helped me to catch things that normally I wouldn't even think about. For example, if a method does not reference any member variables, one suggestion from FxCop is to mark the method as static, so the method doesn't have to be allocated to every instance of the class. From MSDN:

Methods that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

Prefixing my member variables with 'this.' does two things for me. First, it satisfies StyleCop. Secondly, and more importantly, it helps me to quickly identify if a method needs to be marked static.

Of course, running FxCop will tell me if I need to mark a method as static. However, using 'this.' helps me spend more time writing new code and less time remedying FxCop violations.

Aaron Daniels
This only applies to that rare performance-sensitive code, though. Generally, whether a function is static or not is a matter of contract. One should not make a function static just because in the current implementation it does not need to access class members. It might need to in future, when other code relies on it being static.
Don Reba
+9  A: 

No. I consider it visual noise. I think the this variable is a crutch to bad naming styles. Within my type I should be able to manage the naming of the fields, properties and methods.

There is absolutely no good reason to name your backing field "myfield", the parameter to the constructor as "myField" and the property to be "myField".

 public class TestClass
 {
    private string myField;
    public TestClass(string myField)
    {
      this.myField = myField;
    }
    public string MyField {get { return myField;} set {myField = value}}
 }

Personally, I always add a prefix of _ to all my private backing fields.

 public class TestClass
 {
    private string _myField;
    public TestClass(string myField)
    {
      _myField = myField;
    }
    public string MyField {get { return _myField;} set {_myField = value}}
 }

and now with automatic properties in C#

 public class TestClass
 {
    private string MyField {get; set;}
    public TestClass(string myField)
    {
      MyField = myField;
    }
 }

Other than the above maybe the only other time you type this. is because you want to see the intellisense for your current type. If you need to do this then I submit that your type is too big and probably not following the Single Responsibility Principle. And lets say you are. Why keep the this. around after you actually make the call. Refactor it out.

Robert Kozak
A: 

I do, for me it adds a bit of clarity to the code, is it in the current procedure or the class?

Christopher Kelly
+1  A: 

Yes, if I see this. I'm sure it is local and I do not need to look any further. If it isn't prefixed with this. (or maybe '_') I have to check if it is declared locally or in an ancestor or if it's a parameter or ...

All these checks take a little more time during debugging...

Janco
A: 

I do a lot simply because it makes the autocompletion pop up.

KevMo
+1  A: 

Generally yes, I do. Communicating scope is an important aspect of readability. It distinguishes it from local variables, static methods, etc. It also communicates that the definition is "nearby".

Oh, and I only do it for public methods/properties. Those tend to be capitalized so this.Thing looks right. The internal view looks like the external view (myInstance.Thing). Private properties are often lowercase and so it's a less attractive idea for those.

It's not strictly necessary of course, and some people prefer it more terse. But it provides hints to me and other devs who might look at the code.

Matt Sherman