How can I enforce code styles for C#/.NET, like IDE0058, IDE0059 and IDE0060?

Viewed 367

I'm looking into enforcing code styles and to start I implemented IDE0058, IDE0059 and IDE0060 in my .editorconfig, like so:

csharp_style_unused_value_expression_statement_preference = discard_variable:error
csharp_style_unused_value_assignment_preference = discard_variable:error
dotnet_code_quality_unused_parameters = all:error

When I run build in visual studio 2022 on windows I do get errors for them, although the build still succeeds. However, when I run dotnet build from the command line, I don't get any errors and when I searched for the style codes, I couldn't find any mention of them.

My colleague tested it on his macbook, and the mac version of visual studio didn't give any errors. Neither did the command line.

In our gitlab pipeline we also run dotnet build, which also passed without any errors.

In all environments we are using .NET 6.0.

Is it possible to enforce these code styles using .editorconfig? If so, how?

If not, how can code styles be enforced?

2 Answers

Add following lines to csproj file

<PropertyGroup>
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
    <AnalysisLevel>6.0-recommended</AnalysisLevel>
</PropertyGroup>

Then in editorconfig additionally to your existing rules add

dotnet_diagnostic.IDE0058.severity = error
dotnet_diagnostic.IDE0059.severity = error
dotnet_diagnostic.IDE0060.severity = error

You need to enable the project properties:

  1. Right-click the project
  2. Click "Build"
  3. Set Treat warnings as errors to All:

Treat warnings as errors: All

However, if you do it, it'll be added only for current configuration which is probably Debug.

You can do it manually via UI for both configurations (Debug and Release).

Or you can edit your .csproj file.

This will be added if you set Treat warnings as errors: All via UI.

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <WarningsAsErrors />
  </PropertyGroup>

You can duplicate it and change the configuration:

ded if you set Treat warnings as errors: All via UI.

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> // Changed `Debug` to `Release`
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <WarningsAsErrors />
  </PropertyGroup>
Related