views:

66

answers:

3

When should I use the this-keyword for properties in code?

public class MyClass {
    public string MyString { get; private set; }
    public void MyMethod() {
        OtherClass.DoStuff(MyString); // Or this.MyString?
    }
}

I know that if the type and name of a property is the same you have to use this. to make it work.

public string Emailer Emailer { get { return _emailer; } }

What are the guidelines for using this. on Properties and even Methods in a class? I know it makes no difference in the compiled code. It's all about... hold your breath... best practices.

+2  A: 

Do whatever you and your team find most readable. Some people like to be explicit; I only specify this when I actually have to. It will make no difference to the compiled code.

Jon Skeet
The question is mostly asked to get some hints on how to justify why one is more readable than the other.
Seb Nilsson
@Seb: It's really just personal preference - do you like very compact code where occasionally you might have to think a little more to understand whether you're using an instance variable or a local variable... or do you prefer longer, more explicit code?
Jon Skeet
@Jon Aaah, "explicit", that was a keyword that helps me out in my underlying question. Mention it in your answer and get the regular Skeet-check-mark :P
Seb Nilsson
@Seb: Look at the second sentence: "Some people like to be **explicit**."
Jon Skeet
@Jon I'm a developer, I never read the second sentence! ;)
Seb Nilsson
+2  A: 

If a parameter name and an instance member have the same name, you will need to use this.

Like:

public class MyClass
{
    private string something;

    public void SomeMethod (string something)
    {
        this.something = something;
    }
}

But I'd advice you to choose names in that fashion that you'll never need to use this. Doing otherwise is just asking for trouble - sooner or later you'll forget this somewhere and will have a hard time debugging your code.

Developer Art
A: 

Whether or not to use this is mostly an issue of preference and hence there is no right or wrong answer. It can become a bit of a religous war though with devs. I often find it's best to come to an agreement on the team one way or the other and use StyleCop to enforce the decision afterwards.

Personally I prefer brevity and only use this when it's actually necessary. But I'd choose code base consistency over my personal preferences here because it's a fairly minor issue.

There are a few cases where it's explicitly needed. Extension methods on this and in certain cases to disambiguate an identifier come to mind. I find these are fairly rare though.

JaredPar