Search code examples
c#.netlintcode-formatting

Is there a comprehensive C# linter and formatter like eslint for JS/TS?


I'd like to have my C# projects (.NET Core 3.1+) to be linted and formatted on each build both locally and in CI environment. I know that there's new .NET Analyzers feature and dotnet-format tool in .NET 6, but I can't understand from the documentation if I can make a single comprehensive configuration file that both these tools would use so I can enforce certain code style in my team. Could you help me understand if it is possible?


Solution

  • Yes there is - Roslyn Analyzers.

    With a EnforceCodeStyleInBuild element set in your .csproj:

      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
    
        <!-- this! -->
        <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
      </PropertyGroup>
    

    an .editorconfig file in your project, which you can get like this:

    dotnet new editorconfig
    

    and updating your VS Code settings.json to include:

    {
      "omnisharp.enableRoslynAnalyzers": true,
      "omnisharp.enableEditorConfigSupport": true
    }
    

    And you should be off to the races! I've written this up in more depth here:

    https://johnnyreilly.com/eslint-your-csharp-in-vs-code-with-roslyn-analyzers