Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท .NET, Tools and Concepts

Analyzers and code style

Reference for Roslyn analyzers in C#: diagnostic IDs (CS, CA, IDE), severity in .editorconfig, AnalysisLevel, pragma and SuppressMessage, and writing your own.

A Roslyn analyzer is a library that plugs into the C# compiler and inspects your code while you type and while you build. Each rule it implements produces a diagnostic with an ID, a severity, a message and a location. The compiler itself is also a source of diagnostics, such as unused-variable warnings, but its rules are built in, while analyzers come as packages or as part of the SDK.

Analyzers cover three jobs: finding bugs (a disposable that is never disposed), enforcing good practice (use ArgumentNullException.ThrowIfNull), and enforcing style (naming, braces, var). Many have a code fix: a lightbulb action in the editor that changes the code for you.

INI
# .editorconfig
[*.cs]
dotnet_diagnostic.CA1822.severity = warning
dotnet_diagnostic.IDE0005.severity = suggestion
csharp_style_var_for_built_in_types = false:suggestion

Try it

The runner has no MSBuild, so there are no .editorconfig or project settings here. The compiler's own diagnostics and the #pragma and attribute controls work the same everywhere.

C# Suppressing a diagnostic with #pragma

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Diagnostics you get without any analyzer package

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

Where diagnostic IDs come from

Prefix Source Example
CS The C# compiler CS0168 unused variable, CS8602 possible null dereference
CA .NET code analysis (quality, design, performance, security) CA1822 mark members static, CA2000 dispose objects
IDE Code style rules (editor and build) IDE0005 remove unnecessary using, IDE0090 simplify new
SYSLIB Platform obsoletion and source generator diagnostics SYSLIB1045 use [GeneratedRegex]
other Packages: xUnit xUnit1000, StyleCop SA1000, Roslynator RCS1000

Severity levels

Severity Effect
error The build fails
warning Reported in the build output
suggestion Shown in the IDE, not an error or warning in the build
silent No visible report, but a lightbulb fix may still be offered
none / default Disabled / the rule's built-in severity

Set a rule: dotnet_diagnostic.CA1822.severity = warning in .editorconfig. Set a whole category: dotnet_analyzer_diagnostic.category-Performance.severity = warning. Style options such as dotnet_style_qualification_for_field = false:suggestion use the form option = value:severity.

Project properties

Property Effect
AnalysisLevel Which set of analyzer rules is on by default (latest, latest-recommended, 10.0, latest-all)
AnalysisMode Default, Minimum, Recommended, All, None
EnableNETAnalyzers The built-in .NET analyzers (on by default for .NET 5+)
EnforceCodeStyleInBuild Run the IDE rules during a build, not only in the editor
TreatWarningsAsErrors Every warning fails the build
WarningsAsErrors / WarningsNotAsErrors Specific IDs or categories (for example nullable)
NoWarn Silence specific IDs for the project

Suppressing

Method Scope
#pragma warning disable ID ... restore A region of code in a file
[SuppressMessage(category, checkId, Justification = "...")] A member or type, includes a written reason
.editorconfig severity none A folder, project or file pattern
GlobalSuppressions.cs Assembly-wide

Writing an analyzer

An analyzer is a separate class library that references Microsoft.CodeAnalysis.CSharp, targets netstandard2.0, and is packaged for consumers. This sketch is read-only because the runner has no NuGet or MSBuild.

C#
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class NoConsoleAnalyzer : DiagnosticAnalyzer
{
    private static readonly DiagnosticDescriptor Rule = new(
        "DEMO001", "Avoid Console", "Do not call Console.{0}",
        "Design", DiagnosticSeverity.Warning, isEnabledByDefault: true);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule];

    public override void Initialize(AnalysisContext context)
    {
        context.EnableConcurrentExecution();
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.RegisterOperationAction(ctx =>
        {
            var call = (IInvocationOperation)ctx.Operation;
            if (call.TargetMethod.ContainingType.Name == "Console")
            {
                ctx.ReportDiagnostic(Diagnostic.Create(Rule, call.Syntax.GetLocation(), call.TargetMethod.Name));
            }
        }, OperationKind.Invocation);
    }
}

Usage notes

  • Warnings are cheap to ignore and expensive to accumulate. Keep the build at zero warnings, then turn on TreatWarningsAsErrors (or WarningsAsErrors) in CI.
  • Share one .editorconfig at the repository root. It applies to every IDE and to dotnet build, so the whole team gets the same rules. Add root = true at the top.
  • Prefer a narrow suppression. #pragma around one line or [SuppressMessage] with a justification beats a global NoWarn, which hides future real problems too.
  • IDE rules run only in the editor by default. Set EnforceCodeStyleInBuild to true to make style violations show up in dotnet build.
  • dotnet format applies the style and analyzer fixes from the command line (dotnet format analyzers, dotnet format style).
  • Analyzers do not run at run time and change nothing about the compiled program. They only report.
  • Generated code (files named *.g.cs, code marked [GeneratedCode]) is usually excluded from analysis.
  • Beware stale #pragma disable without restore: the warning stays off for the rest of the file.