Subjective usages of 'this' in C# [closed]
I开发者_如何学编程 come from C++ and normally this
is rarely used compared to C#. In my experience, the usage of this
is strictly limited to scope and/or name resolution.
I have coworkers that insist that using this
everywhere makes code "more clear". They essentially depend on it for documentation purposes. I disagree with this usage as it is very subjective, redundant, and practically useless as far as documentation is concerned.
There are cases where I see this.myClassVariable = 100;
. In this case, this
serves no real use other than (according to my coworkers) to make it very clear that myClassVariable
is not a static. This is just one example.
Personally, where ever there are no ambiguities, I use myClassVariable = 100;
. This is more clear and I feel honestly that if your variables are well named, code will be self documenting and 'this' is not needed.
What is the general rule of thumb on using 'this'? I'm asking for use cases that go beyond the obvious requirements (such as resolving ambiguities). There are cases where the usage of this
is required for code to compile and I'm not necessarily interested in those cases. How do you guys feel about using this
for documentation?
If they want to distinguish static variables from private instance variables, why not use a naming convention to distinguish the two, instead of requiring this
? For example, for private instance variables, prefix them with an underscore and name them using camel case (e.g. _myVariable
). Then, for static variables, use Pascal case with no prefix (e.g. MyStaticVariable
). It allows for simple disambiguation between static and instance variables, and doesn't require the extra key strokes and general "ugliness" required for this
.
I personally strongly object to this usage. Makes refactoring very hard - if you want to change a variable to a static or a local, you have to go through all usage points and get rid of this.
.
This usage was possibly motivated by PHP or Python where it's a must.
精彩评论