Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have been trying to follow StyleCop's guidelines on a project, to see if the resulting code was better in the end. Most rules are reasonable or a matter of opinion on coding standard, but there is one rule which puzzles me, because I haven't seen anyone else recommend it, and because I don't see a clear benefit to it:

SA1101: The call to {method or property name} must begin with the 'this.' prefix to indicate that the item is a member of the class.

On the downside, the code is clearly more verbose that way, so what are the benefits of following that rule? Does anyone here follow that rule?

like image 731
Mathias Avatar asked Oct 13 '09 19:10

Mathias


People also ask

Why is Stylecop used?

StyleCop analyzes C# source code to enforce a set of style and consistency rules. Use it as a NuGet package which is the best way to work in a team.


2 Answers

I don't really follow this guidance unless I'm in the scenarios you need it:

  • there is an actual ambiguity - mainly this impacts either constructors (this.name = name;) or things like Equals (return this.id == other.id;)
  • you want to pass a reference to the current instance
  • you want to call an extension method on the current instance

Other than that I consider this clutter. So I turn the rule off.

like image 92
Marc Gravell Avatar answered Oct 12 '22 16:10

Marc Gravell


It can make code clearer at a glance. When you use this, it's easier to:

  • Tell static and instance members apart. (And distinguish instance methods from delegates.)
  • Distinguish instance members from local variables and parameters (without using a naming convention).
like image 38
Jeff Sternal Avatar answered Oct 12 '22 18:10

Jeff Sternal