开发者

C# "this" overuse? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

When do you use the “this” keyword?

I'm writing some of my first C# code, and I notice that this.foo is only necessary when there is a local name foo different from the this.foo. I have so far been inconsistent as to whether or not I use this.

Is it preferred to alw开发者_如何转开发ays use this or is it preferred to only use this when necessary?


I only use this when it is necessary. Most of the time I don't have the issue of having to differentiate between a local and class variable, so I just don't bother unless the need comes up


I always type 'this' because it allows me to use Visual Studio's Intellisense. I don't think that there is any meaningful stylistic objection to using 'this' for each reference to an object property or method.


It's really a matter of style - some people like to use this all the time, since it makes it clear when you're accessing a member variable instead of method local, some people use warts on the name for the same purpose, and some people don't use either.

Regardless, it's probably a bad idea to use the same name for a method local as for a member variable - the only time I'd consider it legitimate is when setting those members in the constructor or other initialization routine.


I do prefer it because of clarity. But also because we follow StyleCop's rules (almost all of them :) ).

Why does StyleCop recommend prefixing method or property calls with "this"?


It's based entirely on your preference. I personally like to use it all the time to emphasize that it's a class variable, but that's just me.


I use this when I want to clarify my intent.

But generally, the Visual Studio IDE will clarify the member for you (with a popup) if you hover over the member in question. That reduces the need for this.

As Adam points out, typing this first will intellisense only the local members for you, instead of giving you the entire intellisense list.


Just to give an answer that contrasts with the many "pro this" answers...

I almost never use this. I prefix all member variables with an underscore, and so I can easily tell local and member variables apart. I find using this all the time really pollutes the code and makes it far more noisy.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜