Closed marcvannieuwenhuijzen closed 1 year ago
Although we acknowledge that this is a common request, we don't like that convention and preach against it. But the beauty of this website is that you can fork it and adopt it to your own needs. For example, one of my clients also adopted it at some point, simply because the code is legacy and easy to misunderstand.
Thx for your quick reply. It would be interesting to know why your preach against it. I would really like to understand the arguments for not using the underscore. Is there another issue where this was discussed previously?
Exactly for the reason you mentioned in your opening. If you need it, you class is doing too much.
@dennisdoomen why not follow Microsofts convention/standard? It looks like their recommendation is to prefix private fields with . https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names#naming-rules "Private instance fields start with an underscore ()."
Much of the code from Microsoft was written 20 years ago. For them it's more important to stick with a convention than to introduce diffs, unless there's substantial benefit. Interestingly, the new primary constructor syntax in C# votes against using underscores. That's because the method parameters become auto-generated fields.
In the end, it comes down to a matter of personal preference. The guidelines here define standards to make code bases consistent in many aspects, and that's what matters most. The nice thing about them is it forces you to think about many stylistic choices, and then anyone can adapt to what feels best and share with the team.
For people dealing with legacy code bases: there's a fixer in StyleCop that can be run solution-wide to change the style of private fields with just a few clicks.
For people dealing with legacy code bases: there's a fixer in StyleCop that can be run solution-wide to change the style of private fields with just a few clicks.
Just add the necessary settings to your .editorconfig
and run an auto-format (using a decent IDE such as Jetbrains Rider)
This would make it easier to distinguish private fields from method arguments.
I know that when methods are small it should still be obvious which one it is. But the sad fact is that in old codebases not all guidelines are implemented yet. One may start by giving better names to arguments and fields to improve readability. Until a method is refactored to be smaller in size, the underscore can help to make the big method easier to understand.