Skip to content

Compile Time Style Enforcement

Enforce code style rules at compile time so the project fails to build if violations exist.

RuleDescription
No varUse explicit types instead of var
No unused usingsRemove unnecessary using directives
Collection expressionsUse simplified collection syntax like List<string> names = []
CancellationToken forwardingForward CancellationToken to methods that accept it

Create .editorconfig in the solution or project root:

root = true
[*.cs]
# Use explicit types instead of var (IDE0008)
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
csharp_style_var_elsewhere = false:error
dotnet_diagnostic.IDE0008.severity = error
# Remove unnecessary usings (IDE0005)
dotnet_diagnostic.IDE0005.severity = error
# Use collection expressions (IDE0028, IDE0300, IDE0305)
dotnet_style_collection_initializer = true:error
dotnet_style_prefer_collection_expression = true:error
dotnet_diagnostic.IDE0028.severity = error
dotnet_diagnostic.IDE0300.severity = error
dotnet_diagnostic.IDE0305.severity = error
# Forward CancellationToken to methods (CA2016)
dotnet_diagnostic.CA2016.severity = error

Add these properties to your .csproj:

<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
PropertyPurpose
TreatWarningsAsErrorsFails build on any warning
EnforceCodeStyleInBuildEnables IDE rules (IDE0005, IDE0008, etc.) during build
GenerateDocumentationFileRequired for IDE0005 (unused usings) to work
NoWarn=1591Suppresses “missing XML comment” warnings from doc generation

Use dotnet format to automatically fix violations:

Terminal window
# Fix all style issues
dotnet format
# Fix a specific rule
dotnet format --diagnostics IDE0008 --severity error
// Bad
var name = "Michael";
var count = 42;
// Good
string name = "Michael";
int count = 42;

Removes using directives that are not referenced in the file.

IDE0028/IDE0300/IDE0305 - Collection expressions

Section titled “IDE0028/IDE0300/IDE0305 - Collection expressions”
// Bad
List<string> names = new List<string>();
List<int> numbers = new List<int> { 1, 2, 3 };
// Good
List<string> names = [];
List<int> numbers = [1, 2, 3];
// Bad - cancellationToken exists but not forwarded
async Task DoWorkAsync(CancellationToken cancellationToken)
{
await client.SendAsync(request);
}
// Good
async Task DoWorkAsync(CancellationToken cancellationToken)
{
await client.SendAsync(request, cancellationToken);
}