Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.


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


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://docs.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