How do I customize Visual Studio's private field generation shortcut for constructors?
Asked Answered
C

4

228

VS 2017 (and maybe olders versions) gives me this handy little constructor shortcut to generate a private readonly field and assign it.

Screenshot:

enter image description here

This ends up generating a private member called userService and then assigns it with:

this.userService = userService;

This goes against the code style that I use which is to name all private members with a prefix _ resulting in assignment that should look like:

_userService = userService;

How can I make it so that VS obeys this code style rule with its code generation shortcuts?

Comyns answered 17/8, 2017 at 13:36 Comment(4)
This doesn't have anything to do with snippets, this feature is provided by the code analysis service. Available since Roslyn was added. A leading underscore is a violation of the .NET Framework Programming Guideline, no way that you are going to talk a Microsoft programmer into changing this. It is a style pushed by Resharper, they don't like this. because that makes programmer not buy it, consider using it.Darlenedarline
@HansPassant Every piece of modern code I have seen produced by the teams at Microsoft follow this _camelCase convention for private members. See the CoreFX C# Coding Style Guidelines, ASP.NET Core Coding Style and even Rosyln code itself...??Comyns
@HansPassant Good news ... someone successfully talked a Microsoft programmer into being able to change this. See the answer below.Comyns
Any idea how to do this in Visual Studio for Macs?Haga
L
467

This can be also achieved directly in Visual Studio. Just go to Tools -> Options -> Text Editor -> C# -> Code Style -> Naming.

  1. Firstly you need to define a new naming style by clicking the "Manage naming styles" button:

VS2017 Naming style dialog

  1. Then click the + sign to define a new rule for "Private or Internal Field", that uses your new naming style:

VS2017 Options dialog

  1. Restart Visual Studio

  2. After that, when you apply the "Create and initialize field" refactoring, it will be named with a leading underscore.

Linetta answered 2/10, 2018 at 7:15 Comment(11)
I'm on Visual Studio 15.8.8 and this was the only answer here that worked for me.Plainsong
FYI: You may have to restart VS after this.Platysma
Works well in VS 2019.Pilpul
Not all heroes wear capes. Great explanation. Works great! Thx.Goulden
is this available for Visual Studio for Mac?Egoism
No restart required in VS 2019 Version 16.5.4Ethaethan
@MinaFawzy I have looked at Visual Studio for Mac and could not find this customization yetAmice
For some reason I didn't get this solution to trigger in an existing project in VS2019 16.10.4. When I used below answers in .editorconfig it started working. Anyone know why it might not trigger using this answer?Morales
works well on VS 2022 Pre as well. Kudos!Mccrea
it works! VS 2022 Stable (64 bit Version 17.0.2)Mod
for years I have been replacing 'this.' with '_'. This is going to save me that very tedious tasks!Ratchet
R
102

The .editorconfig settings is kspearrin's answer didn't work for me I had to use these (for VS2017 Version 15.4.0):

[*.{cs,vb}]
dotnet_naming_rule.private_members_with_underscore.symbols  = private_fields
dotnet_naming_rule.private_members_with_underscore.style    = prefix_underscore
dotnet_naming_rule.private_members_with_underscore.severity = suggestion

dotnet_naming_symbols.private_fields.applicable_kinds           = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private

dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _

I got these from here: https://github.com/dotnet/roslyn/issues/22884#issuecomment-358776444

Rn answered 22/3, 2018 at 12:9 Comment(9)
Weird. I am now using VS 2017 15.6 and my original answer still seems to work there. Who knows...Comyns
I updated to 15.6.3 and this version stills works for me. I'm using Community edition, maybe you're not?Rn
I can't get either to work, I'm using VS Pro 2017 version 15.6.4Pericynthion
following this also: learn.microsoft.com/en-us/visualstudio/ide/…Pericynthion
This one worked for me when the accepted answer did not. VS Pro 15.7.5Cab
This worked, VS Community 15.8.0. Make sure to close the file you are editing and try different classes in your constructor, for some reason trying the same class wasn't working even after reloading VS.Halonna
Unfortunately, the above setting doesn't work in the web project.Afterbirth
For some reason, it's also applied to const?Aldehyde
Anyway to prevent this from applying to PascalCase private members like "private static readonly" or "private const"?Cobbler
C
42

This can be achieved by creating your own Roslyn Code Analyzer naming rule. Add a .editorconfig in your solution to specify custom naming conventions.

Read more about them here: https://learn.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference

To get the desired effect from the question, the following will work:

[*.{cs,vb}]
dotnet_naming_rule.private_members_with_underscore.symbols  = private_fields
dotnet_naming_rule.private_members_with_underscore.style    = prefix_underscore
dotnet_naming_rule.private_members_with_underscore.severity = suggestion

dotnet_naming_symbols.private_fields.applicable_kinds           = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_symbols.private_fields.required_modifiers         = readonly

dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _

Result:

enter image description here

Comyns answered 23/8, 2017 at 17:24 Comment(7)
This seems to me to be the long way of accomplishing this task. Please see @Linetta 's response.Simms
This was the only way back when I originally answered. Looks like they added a UI for it now.Comyns
Editing .editorconfig is a much nicer solution than doing it via the UI.Boesch
@Simms It's the other way around. Having to tell every member of your team to configure their VS a certain way by hand is definitely much longer, tedious, and error prone than checking in an .editorconfig file in Git and knowing that from that moment on everyone will have their settings automatically adjusted to follow the project's coding style.Oscoumbrian
Unfortunately, the above setting doesn't work in the web project.Afterbirth
I used this answer to remove the underscore requirement that was recently introduced. The underscore private fields are the most abominable and ugliest thing that c# had to endure...Epistyle
Answer addressing VS2022 from @aleksander_si provided insight that the readonly required modifier was preventing the Create and initialize field from working for me.Roncesvalles
F
10

I read the previous solutions and as much as they seem correct, the only way to get the configuration to work correctly in VS2022 is to properly order the .editorconfig entries, as follows:

# Use underscores for private fields
[*.{cs,vb}]
dotnet_naming_symbols.private_fields.applicable_kinds           = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private

dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _

dotnet_naming_rule.private_fields_with_underscore.symbols  = private_fields
dotnet_naming_rule.private_fields_with_underscore.style    = prefix_underscore
dotnet_naming_rule.private_fields_with_underscore.severity = warning
Fuzz answered 18/1, 2023 at 10:3 Comment(3)
See https://mcmap.net/q/120040/-use-different-prefix-for-const-and-non-const-private-members-in-editorconfig to keep const in Pascal case.Marylandmarylee
This worked great thanks!Boyles
This was picked up immediately by Visual Studio 2022. I want to have underscore when I perform a dependency injection in constructor. I was editing the .editorconfig in VsCode and VS 2022 saw my change at once. I also avoided the annoying this. prefix that VS usually adds in front inside constructor. Put aleksander_si block at the top of naming rules at the top of the fileHostetler

© 2022 - 2024 — McMap. All rights reserved.