Why does StyleCop recommend prefixing method or property calls with "this"?
Solution 1
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).
Solution 2
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 likeEquals
(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.
Solution 3
I think this article explains it a little
http://blogs.msdn.microsoft.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx
...a brilliant young developer at Microsoft (ok, it was me) decided to take it upon himself to write a little tool which could detect variances from the C# style used within his team. StyleCop was born. Over the next few years, we gathered up all of the C# style guidelines we could find from the various teams within Microsoft, and picked out all of best practices which were common to these styles. These formed the first set of StyleCop rules. One of the earliest rules that came out of this effort was the use of the this prefix to call out class members, and the removal of any underscore prefixes from field names. C# style had officially grown apart from its old C++ tribe.
Solution 4
this.This
this.Does
this.Not
this.Add
this.Clarity
this.Nor
this.Does
this.This
this.Add
this.Maintainability
this.To
this.Code
The usage of "this.", when used excessively or a forced style requirement, is nothing more then a contrivance used under the guise that there is < 1% of developers that really do not understand code or what they are doing, and makes it painful for 99% who want to write easily readable and maintainable code.
As soon as you start typing, Intellisence will list the content available in the scope of where you are typing, "this." is not necessary to expose class members, and unless you are completely clueless to what you are coding for you should be able to easily find the item you need.
Even if you are completely clueless, use "this." to hint what is available, but don't leave it in code. There are also a slew of add-ons like Resharper that help to bring clarity to the scope and expose the contents of objects more efficiently. It is better to learn how to use the tools provided to you then to develop a bad habit that is hated by a large number of your co-workers.
Any developer that does not inherently understand the scope of static, local, class or global content should not rely on "hints" to indicate the scope. "this." is worse then Hungarian notation as at least Hungarian notation provided an idea about the type the variable is referencing and serves some benefit. I would rather see "_" or "m" used to denote class field members then to see "this." everywhere.
I have never had an issue, nor seen an issue with a fellow developer that repeatedly fights with code scope or writes code that is always buggy because of not using "this." explicitly. It is an unwarranted fear that "this." prevents future code bugs and is often the argument used where ignorance is valued.
Coders grow with experience, "this." is like asking someone to put training wheels on their bike as an adult because it is what they first had to use to learn how to ride a bike. And adult might fall off a bike 1 in 1,000 times they get on it, but that is no reason to force them to use training wheels.
"this." should be banned from the language definition for C#, unfortunately there is only one reason for using it, and that is to resolve ambiguity, which could also be easily resolved through better code practices.
Solution 5
Note that the compiler doesn't care whether you prefix references with this
or not (unless there's a name collision with a local variable and a field or you want to call an extension method on the current instance.)
It's up to your style. Personally I remove this.
from code as I think it decreases the signal to noise ratio.
Just because Microsoft uses this style internally doesn't mean you have to. StyleCop seems to be a MS-internal tool gone public. I'm all for adhering to the Microsoft conventions around public things, such as:
- type names are in PascalCase
- parameter names are in camelCase
- interfaces should be prefixed with the letter I
- use singular names for enums, except for when they're [Flags]
...but what happens in the private realms of your code is, well, private. Do whatever your team agrees upon.
Consistency is also important. It reduces cognitive load when reading code, especially if the code style is as you expect it. But even when dealing with a foreign coding style, if it's consistent then it won't take long to become used to it. Use tools like ReSharper and StyleCop to ensure consistency where you think it's important.
Using .NET Reflector suggests that Microsoft isn't that great at adhering to the StyleCop coding standards in the BCL anyway.
Mathias
I was a quantitative models guy, but California turned me into a software developer. I primarily write code in F#, with origins in C#, and, even further back, VBA for Excel.
Updated on July 05, 2022Comments
-
Mathias almost 2 years
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?
-
Mathias over 14 yearsAgreed about the class fields vs. local variables. The _ or m_ notation for class fields looks like an archaism to me, and this rule is a reasonable way to replace it while keeping things readable.
-
Mathias over 14 yearsThanks, nice to have the inside story!
-
mrkurtan over 14 yearsWhile this answers the question "Why is this a good style rule", the link provided by jayrdub provides a better answer to the question "Why does StyleCop enforce this rule".
-
David R Tribble over 14 yearsYou can accomplish exactly the same thing by using unique affixes on member variables (e.g.,
m_name
versusname
) and none on local and parameter variables. It's a question of taste, though. -
Ian Ringrose over 14 years.NET Reflector does not show you the source code as written, e.g. it's output tells you very little about the sytle of the code, it is a decompiler after all.
-
Drew Noakes over 14 years@Ian - you're right that
this
gets compiled away, but other things such as fields with underscore prefixes remain. If you check the source code that MS now allows you to download (and tools like ReSharper navigate to) you'll see varying coding styles across the BCL too. -
John Saunders about 14 yearsFine, but once you're done getting the list,
this.
is no longer of any value. Consider: if there were a keystroke you could type that would produce the same IntelliSense list as typing "this.
", then there would be very little need to type "'`this.'". -
John Saunders about 14 yearsThanks for the link. It tells me why the StyleCop rules are largely crap - they're a bunch of rules from scattered teams, and not a single, well thought-out set of rules, researched to determine that they are, in fact, best, for teams of all levels of ability.
-
krystan honour about 14 yearsI have heard this particular excuse before, hitting this. for intellisense to me just smacks of lazyness as the this. is not required as the previous comment points out. Plus there are other ways to invoke intellisense.
-
jpierson about 13 years@Loadmaster - I would add too that with the use of an affix/prefix such as underscore, it enforces usage through the name whereas with the 'this' keyword you have to rely on tools like StyleCop to enforce the usage.
-
jpierson about 13 yearsI see this practice often within constructors where many times the parameters match the names of various private fields and or properties to which adding the 'this.' prefix helps to clarify the code and in some cases avoid name collisions.
-
jpierson about 13 yearsFor the same reason I used to type '.' in Java code because, if I remember correctly, tools like JBuilder would pick it up and offer intelli-sense. So I think in Jave the kewword 'this' can be committed altogether.
-
Bender over 9 yearsYour last paragraph essentially contradicts your 3rd point. And anybody who's a touch typist and has the move out of the home position to get to the underscore key is... not a touch typist.
-
Bender over 9 yearsOops, typo. "has to move out of... " It won't let me edit my comment after 5 minutes.
-
Sean almost 9 yearsIf you're using
this
to distinguish members then you're basically using a naming convection, so it's no better than prefixing with_
orm_
. In fact it's worse as usingthis
requires more characters. -
Cogwheel over 8 yearsVisual studio suggests removing the "this" that stylecop suggested I add. Can't they make up their minds?
-
Stefan Sieber almost 8 yearswell put. I couldn't think of any bug we had the last few years due to the missing 'this'. Nice comparison with the training wheels :)
-
BlueRaja - Danny Pflughoeft almost 7 yearsOr use syntax-highlighting that differentiates these things, then you get the benefits without the clutter
-
Craig over 6 yearsWell put. Unnecessary clutter as far as I'm concerned.
-
Philip Vaughn over 5 yearsThis is absolutely the correct response. Having "this" all over your code is stupid and it's never taught anywhere.
-
person27 over 4 yearsWell in 2019 anyway, stylecop.analyzers seems to have some pretty strong rules and I leave most enabled; only a few like this and banning #region are really questionable. Would like better customization and coverage of a few other things e.g. line length as part of the ruleset, but for the most part, it's great. I mean, I'm only here because I look up the merit of every rule.
-
spikey_richie over 3 yearsNov 4th 2020, link is broken.
-
benJephunneh over 2 yearsMicrosoft's Coding Conventions say to use the
_
prefix for the private and internal fields. It seems IntelliSense is also looking out for the underscore, specifically. -
Chris Fremgen almost 2 years8 years later, "this." is much more popular thanks to TypeScript. Underscore looks terrible, and you can' differentiate between instance classes, methods, or properties.