开发者

C# Properties and this-keyword

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

public class My开发者_开发问答Class {
    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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜