views:

501

answers:

7

Let me give you an example:

public class MyClass
{
    public string MyProperty { get; set; }

    public MyClass(string myProperty)
    {
        MyProperty = myProperty; // bad?
        this.MyProperty = myProperty; // good?
    }
}

I've taken to using this in this scenario, because I have minor paranoia that relying on case alone might be confusing or worse might actually lead to bugs.

What is the "best practice" here?

EDIT:

So far, it sounds like this is a lot more subjective than I thought. I figured people would come down strongly on one side or the other.

+12  A: 

Using "this." is redundant in any class. It's totally up to your development shop to set a standard for using it.

The pros of using "this." are that some developers find it easier to associate it in their mind with the class instance when they are reading the code, and as you mention, make it clearer when dealing with similarly named items.

The cons are that some people view it as cluttering up your code file and if you use tools like ReSharper, they mark it as redundant code by default.

womp
BTW - Resharper has options to force this, especially if you use something like StyleCop for Resharper.
Reed Copsey
"this" is not entirely redundant. If you have a local variable named "myThing" and an instance variable named "myThing", then "myThing" references the local variable, and "this.myThing" references the instance variable.
Jim Mischel
My recollection is that `this.myVariable` is recommended to avoid the use of Hungarian notation. In this case, `this.myVariable` is recommended over `m_myVariable`.
Steve Guidi
@Steve Guidi...but probably not preferable to using just an underscore (as in `_myVariable`), which seems to be very common practice even though not officially endorsed by MS.
DanM
@Jim Mischel - good point, it does have a use as a scope qualifier. But that also points out a potential code "smell".
womp
@womp - "code smell". Which was the point of my answer. As far as I'm concerned, the best practice for this is "Don't do that."
Jim Mischel
@womp, what do you suggest as an alternative. The scenario in my question is what happens if you follow standard naming guidelines. How do you suggest disambiguating passed-in local variables from like-named properties? As I say in a comment below, using something like `localMyProperty` is basically Hungarian notation...wouldn't that also be a code smell (or at least bad style)?
DanM
I find "this" useful. I also use "base" and "NameOfClass" (for static variables).
Jodi
@Dan - I'm not suggesting that "this" is bad, I'm just saying it varies widely what people adopt (as you can see). If your programmers are always passing in variable names that are the same as the property names, and you're finding it impossible to disambiguate, you should definitely adopt it. I would not suggest Hungarian, that's pretty much universally despised except for a few cases nowadays.
womp
@Womp, I think I misunderstood what you were saying was a code smell. Having a local variable and a backing field with the exact same name *and* case would probably qualify as a "code smell". This is why I use an underscore for all my fields.
DanM
@DanThMan - yes that's what I was referring to (my comment was directed at Jim's description of instance and local variables being named the same). If it at all matters, our shop also uses underscores to prefix private fields as well, and we don't use "this".
womp
for me if you have an instance variable names myVariable and a member called myVariable this is a code smell and should be refactored.
krystan honour
A: 

Both of your options rely on case alone.... There is no difference between either.

Robin Day
Sure there is. One has 5 extra characters that are read by whoever is viewing the code, which may help or hinder the reader's comprehension.
Brian
Wait, but wouldn't it actually *fail* to say `MyProperty = this.myProperty?`. In other words, doesn't `this.` guarantee that what comes after it is a class-level property or variable? If yes, how can you say the only difference is case?
DanM
+5  A: 

As womp said. "this" is redundant but it makes the code easier to read. Or rather harder to misread.

Sani Huttunen
A: 

In my opinion, the "best practice" here is, "don't do that." If I run across that in code I'm reviewing, I immediately flag it. Having two variables that differ only by case is a misunderstanding just waiting to happen. It's just too easy for a maintenance programmer to come along months or years later and inadvertently make an assigment to myThing instead of MyThing.

Added later:

A commenter asked for my suggestion to replace the upper/lower case naming convention. For that I need a concrete example. Say you have a simple Book class that has only one property: Title:

public class Book
{
    public string Title { get; private set; }
}

Now you need a constructor. A common convention is to use a lowercase version of the property:

public Book(string title)
{
    Title = title;
}

Or, if you want to make sure there's no ambiguity: this.Title = title.

One can make the argument that this is okay in constructors. And it might be, if all constructors were so simple. But my experience has been that when a constructor goes beyond just a few lines, the distinction between Title and title gets lost. The problem becomes worse when you're talking about methods other than constructors. Either way, you need a different convention.

What to use? I've variously used and seen used abbreviations in the parameters: ttl, for example. Or something like bookTitle, which is more descriptive when using Intellisense. In my opinion, either is preferable to the convention of using a name that differs only by case.

Jim Mischel
Do you have a naming convention that avoids this problem? I hate to start naming all my locals `localMyThing`. It's basically Hungarian notation.
DanM
It's trivial to set up StyleCop so that any references to properties (and fields) must be qualified by `this`, which renders the "too easy to inadvertently assign the wrong thing" argument moot.
Pavel Minaev
@Jim, thanks for clarifying. I like `bookTitle`.
DanM
@Pavel: sure, it's trivial to set up StyleCop to do that. If you don't think that forcing the use of "this" is an unreasonable burden. If you do that, you might as well also force full specification on all references. That is, no more Thread.Sleep(10), but rather System.Threading.Thread.Sleep(10). Also: it's equally trivial for a programmer to skip using StyleCop. When you use them, tools like StyleCop are great for enforcing conventions. But they're too easy to circumvent.
Jim Mischel
+2  A: 

C# is definately case sensitive so there is no risk in using...

MyProperty = myProperty;

So then I would look to other best practices like writing the least amount of code needed to achieve your goal (while being self documenting). The truth is, it's not required, minimalists might say leave it out.

+1  A: 

At my workplace, coding standards dictate that properties be written LikeThis while local variables be written likeThis. As C# is case sensitive, this is a good tool to utilize to distinguish your variables apart. If, however, you find yourself with a property and local variable with the exact same name, using the this keyword will definitely disambiguate the usage.

Secret Agent Man
+1  A: 

Here's how I currently initialize properties using your example (both auto-implemented and not)

        public class MyClass
    {
        public string MyProperty { get; set; }

        public string AnotherProperty
        {
            get { return _anotherProperty; }
            set { _anotherProperty = value; }
        }
        private string _anotherProperty;

        public MyClass(string myProperty, string anotherProperty)
        {
            MyProperty = myProperty; // auto-implemented property initialization
            _anotherProperty = anotherProperty; //property with member variable initialization                
        }
    }

Dotting in using 'this' is over specification to me. I know that it's a local property because it is capitalized. All properties should be capialized. I know that the variable '_anotherProperty' has class scope because of the underscore. I used to omit the underscore from class-level variables. Code is easier for me to read when the underscore is there because I immediately know the scope without having to mouse over the variable to see the declaration in the tooltip from VS. Also, I get the benefit of using the same name for local variables by just omitting the underscore. This makes your initializations look clean. Another benefit of the underscore is that you can type an underscore and press ctrl+space and all of your class-scoped variables are grouped.

Steve
Thanks, I like your explanation. I definitely use an underscore for backing fields for exactly the reasons you mention. And I never use the `this` keyword unless there is a local variable in the same scope with the same name and different case.
DanM