Search code examples
c#visual-studiovisual-studio-2022editorconfig

How to force visual studio to generate properties using lower case type (i.g., string instead of String)


I am trying to set C# style rule in .editorconfig file in Visual Studio 2022, so it will always generate the code style that I would use in my project.

Currently, VS generates properties or fields using String and Int32 instead of string and int. Although, I am aware that string is an alias of String, I would like to use string and int instead when defining types.

However, when trying to access static methods like String.IsNullOrEmpty(String) I want to use String instead of string. So the style would look like this

public class Test
{
    // use lowercase here (string not String)
    private string _name;

    // use lowercase here (string not String)
    public string Title { get; set; }

    public Test(string name)
    {
        // use uppercase here (String.IsNullOrEmpty(name) not string.IsNullOrEmpty(name))
        if (String.IsNullOrEmpty(name))
        {
            throw new Exception("...");
        }

        _name = name;
    }
}

What rules can I add to the .editorconfig file to allow Visual Studio 2022 to follow the above style?


Solution

  • From the documentation found here

    When setting dotnet_style_predefined_type_for_locals_parameters_members to true VS will prefer the language keyword for local variables, method parameters, and class members.

    When setting dotnet_style_predefined_type_for_member_access to false VS will prefer the framework classes.

    In short, you need to add this to the .editorconfig file

    dotnet_style_predefined_type_for_locals_parameters_members = true
    dotnet_style_predefined_type_for_member_access = false
    

    Optionally, you can enforce the code style in your project either by using warning of error. warning will show you an a curly line under the non-compliant type, while error force the compiler to fail.

    Here is an example of how to enforce the style using warning

    dotnet_style_predefined_type_for_locals_parameters_members = true : warning
    dotnet_style_predefined_type_for_member_access = false : warning