formattingfieldvisual-studio-macivar

How to change the default naming convention of generated fields in VisualStudio Mac in C#?


I am having a hard time finding this option, if it exists. By default, when VSMac generates a field it creates it as "this.fieldName" I prefer using underscore for iVars so I would like to fix it so that it creates it as "_fieldName" by default. Does anyone know how to accomplish this? I can't seem to find it in the preferences. Thanks.


Solution

  • Visual Studio for Mac has some support for .editorconfig files. The Roslyn refactorings should take this into account.

    If you create an .editorconfig file in the solution directory (you may need to restart Visual Studio for Mac for this to be resolved). Then edit the .editorconfig file so it contains:

    [*.{cs,vb}]
    
    # Instance fields are camelCase and start with _
    dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion
    dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
    dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style
    
    dotnet_naming_symbols.instance_fields.applicable_kinds = field
    
    dotnet_naming_style.instance_field_style.capitalization = camel_case
    dotnet_naming_style.instance_field_style.required_prefix = _
    

    Then, for example, if you create a constructor in your new class:

    class MyClass
    {
        public MyClass(int test)
        {
        }
    }
    

    Then right click the 'test' parameter and select Create and initialize field. Visual Studio for Mac will generate the code:

    public class MyClass
    {
        private readonly int _test;
    
        public EmptyClass(int test)
        {
            _test = test;
        }
    }
    

    Without this .editorconfig file then Visual Studio for Mac would generate the code:

    public class MyClass
    {
        private readonly int test;
    
        public EmptyClass(int test)
        {
            this.test = test;
        }
    }