Skip to content
Tutorials Center
My learning

Topics

Lesson 157 of 182 ยท Testing and Quality

Analyzers, Code Style and Warnings

Learn how Roslyn analyzers, .editorconfig, warning severities, TreatWarningsAsErrors, nullable warnings and dotnet format keep C# code consistent and safe, with real compiler warnings you can run.

A compiler does more than turn C# into IL. While it reads your code it notices things that are legal but suspicious: a variable nobody uses, a possible null dereference, a method that is async but never awaits. It reports these as warnings. On top of the compiler, analyzers inspect your code for deeper problems (a disposable that is never disposed, a string.Compare that depends on the culture) and for style (naming, braces, var). Together they are a tireless reviewer that checks every line on every build, before a human even looks.

In this lesson you will learn how to read compiler warnings, how to fix the most important ones (especially the nullable family), how analyzers and .editorconfig configure severities and style, how to turn warnings into errors in a controlled way, and how to suppress a warning responsibly. Our runner prints the compiler's own warnings with each program, so the warnings below are real. The Roslyn analyzer packages and the dotnet format tool are not available in the editor, so those parts are labelled read-only.

Diagnostics, IDs and severities

Every message the compiler or an analyzer produces is a diagnostic with:

  • an ID such as CS8602, CA1822 or IDE0005,
  • a message,
  • a location (file, line, column) and
  • a severity: error, warning, suggestion (shown in the IDE as grey dots), silent (offered as an IDE refactoring only) or none (disabled).

The ID prefix tells you who produced it:

Prefix Producer Examples
CS The C# compiler itself CS0168 unused variable, CS8602 possible null dereference
CA .NET code-quality analyzers (included in the SDK) CA1822 can be static, CA2000 dispose objects
IDE .NET code-style analyzers (formatting and simplification) IDE0005 unnecessary using, IDE0090 simplify new
SYSLIB Analyzers for the libraries SYSLIB1045 use [GeneratedRegex]
ASP ASP.NET Core analyzers ASP0000 and friends
S, SA, RCS, MA Third-party packages (SonarAnalyzer, StyleCop, Roslynator, Meziantou) S1481 unused local

Searching the ID in your favorite search engine, or in the IDE's light-bulb menu, takes you to a page that explains the rule and shows a fix. Learn to read the ID first; the message second.

Compiler warnings you will meet every day

The editor shows warnings the compiler produced. This program is valid and runs, but the compiler complains about several lines. Run it and look at the warnings panel:

C# A program full of warnings

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.

You should see these in the warnings list (line and column numbers match this exact code):

TEXT
main.cs(3,5): warning CS0168: The variable 'unused' is declared but never used
main.cs(4,5): warning CS0219: The variable 'assigned' is assigned but its value is never used
main.cs(9,1): warning CS0162: Unreachable code detected
main.cs(17,22): warning CS0168: The variable 'e' is declared but never used

and the program prints odd and even. Each of these is harmless on its own, but each means your code does not say what you meant. Perhaps assigned was meant to be used, perhaps a return was added in the wrong place. Treat a warning as a question from the compiler: "Is this really what you wanted?"

A clean build with zero warnings is a valuable asset. With 200 old warnings, a new warning that signals a real bug hides in the noise. Keep the count at zero from the beginning of a project.

The nullable warning family

The most valuable warnings in modern C# come from nullable reference types (enabled by <Nullable>enable</Nullable>; our editor has them on). The compiler tracks which reference variables may be null and warns before a NullReferenceException can happen. If you have not read it yet, see nullable reference types for the concepts. Here we focus on the warnings themselves:

ID Meaning
CS8600 Converting a possibly-null value to a non-nullable type
CS8601 Possible null reference assignment
CS8602 Dereference of a possibly null reference
CS8603 Possible null reference return
CS8604 Possible null reference argument
CS8618 A non-nullable field or property is not initialized when the constructor ends
CS8625 Cannot convert the null literal to a non-nullable type

This program is the classic scenario. A lookup method may return null, and the caller forgets:

C# Ignoring a nullable warning (fails on purpose)

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.

The compiler warns before you even run it:

TEXT
main.cs(1,19): warning CS8602: Dereference of a possibly null reference.
main.cs(2,19): warning CS8602: Dereference of a possibly null reference.

The first line prints [email protected]; the second throws System.NullReferenceException because bob has no email. The warning predicted the crash. Now the repaired version, showing the usual fixes. Look for what the compiler knows after each check:

C# Four honest ways to fix CS8602

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.

No warnings appear, and the output is exactly what each comment says. Two more rules of thumb:

  • The ! operator (the "null-forgiving operator", as in FindEmail("ana")!.Length) tells the compiler "trust me". It removes the warning but not the risk. Use it only where you truly know better than the compiler and, ideally, add a comment saying why.
  • CS8618 is solved by initializing the member, making it nullable (string?), making it required (so callers must set it), or taking it in a constructor (constructors, primary constructors).

Other warnings that point at real bugs

Some warnings catch mistakes that are painful to find later. These two deserve special attention:

C# Warnings that hide real bugs (fails on purpose)

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.

The compiler reports two warnings:

TEXT
main.cs(2,1): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
main.cs(9,46): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'Level.Medium' is not covered.

At run time the output is saving first, saved first, saving second, after the forgotten call, saved second, low, and then the program ends with an unhandled System.Runtime.CompilerServices.SwitchExpressionException ("Non-exhaustive switch expression failed to match its input. Unmatched value was Medium."). Both warnings predicted real problems: the forgotten await lets the second save run unobserved, so after the forgotten call appears in the middle of it, and if SaveAsync had thrown, nobody would ever have seen the exception (see async pitfalls). The switch is missing its Medium arm. A related warning, CS1998, flags an async method that never uses await. Fix the cause (add the missing cases or a _ => arm, await the call, remove needless async) rather than silencing the warning.

Analyzers

A Roslyn analyzer is a small library that plugs into the compiler. It receives the syntax tree and semantic model of your code, reports diagnostics and may provide a code fix (the light bulb that rewrites the code for you). Analyzers run in three places: while you type in the IDE, in the dotnet build command line, and in your CI pipeline, with the same results.

The .NET SDK includes two big sets, both shipping with the SDK so you need no extra package:

  • Code-quality analyzers (CA): correctness, performance, security, reliability. For example:
    • CA1822 a member does not use instance data and can be static
    • CA1861 constant arrays passed as arguments should be cached
    • CA2016 forward the CancellationToken you received
    • CA1848 use LoggerMessage delegates for high-performance logging
    • CA2000 dispose objects before losing the scope (see disposal)
  • Code-style analyzers (IDE): IDE0005 unnecessary using, IDE0051 unused private member, IDE0060 unused parameter, IDE0090 simplify new(...).

You select how strict the built-in rules are in the project file. This is read-only because the editor compiles a single file without MSBuild:

XML
<!-- Read-only: a project file (.csproj) -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>

    <!-- Turn on more of the built-in CA rules: None, Default, Minimum, Recommended, All -->
    <AnalysisLevel>latest-recommended</AnalysisLevel>

    <!-- Run IDE style rules during dotnet build, not only in the editor -->
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>

    <!-- Write XML docs and warn about missing comments on public API -->
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>
</Project>

Third-party analyzers are added as NuGet packages that contain only analyzers. Mark them PrivateAssets="all" so they do not flow to projects that reference yours:

XML
<!-- Read-only: needs NuGet access -->
<ItemGroup>
  <PackageReference Include="Meziantou.Analyzer" Version="*" PrivateAssets="all" />
  <PackageReference Include="SonarAnalyzer.CSharp" Version="*" PrivateAssets="all" />
</ItemGroup>

(Pin real version numbers in practice instead of *.) Popular choices: SonarAnalyzer.CSharp and Roslynator for general quality, StyleCop.Analyzers for strict style and documentation rules, Meziantou.Analyzer for .NET-specific pitfalls, and security-focused packages. Start with the built-ins, add one more only when you know what you want from it.

Writing your own analyzer needs the Roslyn APIs (Microsoft.CodeAnalysis), which are NuGet packages and not available in the editor. It is typically a class deriving from DiagnosticAnalyzer that registers a callback for a kind of syntax node and calls ReportDiagnostic. See source generators and Roslyn for the compiler platform overview.

.editorconfig: severities and style in one file

.editorconfig is a plain text file, understood by Visual Studio, Rider, VS Code and the compiler, that stores style and analyzer settings next to your code. Put it in the repository root; subfolders may add their own files that override it. Sections use glob patterns, and later settings win. A realistic example (read-only):

INI
# .editorconfig - read-only example
root = true

[*.cs]
indent_style = space
indent_size = 4
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

# Language style: value:severity
csharp_style_namespace_declarations = file_scoped:warning
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_prefer_braces = true:warning
csharp_new_line_before_open_brace = all
dotnet_sort_system_directives_first = true

# Naming: private fields are _camelCase
dotnet_naming_rule.private_fields_underscore.symbols  = private_fields
dotnet_naming_rule.private_fields_underscore.style    = underscore_camel_case
dotnet_naming_rule.private_fields_underscore.severity = warning
dotnet_naming_symbols.private_fields.applicable_kinds           = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_style.underscore_camel_case.required_prefix = _
dotnet_naming_style.underscore_camel_case.capitalization  = camel_case

# Analyzer severities
dotnet_analyzer_diagnostic.category-Style.severity = suggestion  # all IDE rules
dotnet_diagnostic.IDE0005.severity = warning                     # unused usings
dotnet_diagnostic.CA1822.severity = suggestion
dotnet_diagnostic.CA2007.severity = none                         # ConfigureAwait: not needed in app code

# Different rules for tests and generated code
[tests/**.cs]
dotnet_diagnostic.CA1707.severity = none      # allow underscores in test names

[**/Migrations/*.cs]
generated_code = true

Three levels of control are useful to remember:

  1. dotnet_diagnostic.<ID>.severity = ... changes one rule.
  2. dotnet_analyzer_diagnostic.category-<Category>.severity = ... changes a whole category (Style, Performance, Security...).
  3. dotnet_analyzer_diagnostic.severity = ... changes everything. The most specific setting wins.

The next program simulates how those rules are resolved, so you can experiment with the precedence. It is a toy parser, not the real thing: the real one lives in the compiler and the IDE.

C# How severity rules are resolved (a toy model)

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.

The first row shows the specific setting IDE0005 = error beating the broader Style = warning. In tests/ the later section lowers it to suggestion. IDE0090 has no rule of its own, so the category setting makes it a warning. CA1822 falls through to the global suggestion, and CA2007 is switched off with none.

Warnings as errors

Warnings that do not break the build are easy to ignore. Two project properties change that:

XML
<!-- Read-only: .csproj -->
<PropertyGroup>
  <!-- Every warning fails the build. Strict; good for new projects. -->
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>

  <!-- Or be selective: only these warnings become errors. -->
  <WarningsAsErrors>$(WarningsAsErrors);nullable;CS8509;CS4014</WarningsAsErrors>

  <!-- Keep a few warnings as warnings even if everything else is an error. -->
  <WarningsNotAsErrors>CS0618</WarningsNotAsErrors>  <!-- Obsolete usage -->
</PropertyGroup>

nullable is a shorthand for the whole nullable family. A reasonable policy:

  • New code: TreatWarningsAsErrors in CI at least. Developers can still see warnings locally while experimenting.
  • Old code with many warnings: don't flip the switch for everything at once. Make specific warnings errors one at a time (nullable first), fix the project, and move on to the next rule.
  • Use the compiler flag only in CI if local experimentation matters: dotnet build -warnaserror.

With warnings as errors, the same code that gave warning CS8602 now stops the build with error CS8602: Dereference of a possibly null reference. and no assembly is produced.

Suppressing warnings responsibly

Sometimes a warning is wrong, or not worth fixing here. Suppress it at the smallest possible scope and always say why.

C# Suppression: pragma, nullable context and the null-forgiving operator

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.

This compiles with no warnings at all and prints legacy is null: True then 5. Without the #pragma lines you would see CS0219 for experiment, and without #nullable disable the line string legacy = null; would give CS8600.

Other forms of suppression:

  • [SuppressMessage("Category", "CA1822:Mark members as static", Justification = "Called through an interface")] on a member, or a project-wide GlobalSuppressions.cs file.
  • dotnet_diagnostic.CA1822.severity = none in .editorconfig for a folder or the whole repository.
  • <NoWarn>CS1591</NoWarn> in the project file to ignore a specific warning (for example missing XML comments).

A suppression without a reason becomes a mystery nobody dares remove. Put a comment or Justification next to every suppression, and prefer narrow scopes: a single line over a file, a file over a project. Never put <NoWarn> with a long list of IDs just to get a build green.

dotnet format and keeping a team consistent

Style arguments (tabs versus spaces, where braces go) waste time. The solution is to let the tools decide and enforce it automatically:

  1. Commit one .editorconfig.
  2. Let every IDE apply it on save.
  3. Run dotnet format to fix existing files and in CI to check them. The command is part of the SDK. It is read-only in the editor, here is how it looks on your machine:
Terminal
dotnet format                                   # fix whitespace, style and analyzer fixes everywhere
dotnet format whitespace                        # only whitespace
dotnet format style --severity warn             # only IDE style rules at warning or above
dotnet format analyzers --severity info         # apply code fixes from analyzers

# In CI: fail if anything would change, change nothing
dotnet format --verify-no-changes
TEXT
Formatted code file '/src/Shop/OrderService.cs'.
Formatted code file '/src/Shop/Money.cs'.

A failing --verify-no-changes prints the files and rule IDs that differ, and exits with a non-zero code so the pipeline turns red. Combine that with warnings-as-errors and a pull request cannot be merged with unused variables, a missing await or an unsafe null dereference.

A sensible starting recipe

For a new project:

  1. Enable <Nullable>enable</Nullable> and <ImplicitUsings>.
  2. Add <AnalysisLevel>latest-recommended</AnalysisLevel> and <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>.
  3. Commit an .editorconfig with your naming and brace rules (the [*.cs] section above is a fine start).
  4. Turn on <TreatWarningsAsErrors>true</TreatWarningsAsErrors> in CI.
  5. Run dotnet format --verify-no-changes in CI.
  6. Add one extra analyzer package only when you can say what problem it solves.

For an old project: enable nullable per file with #nullable enable, fix file by file, then make the nullable warnings errors in the whole project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the ID prefix 'CA' in a diagnostic such as CA1822 tell you?

    CS means the compiler, IDE means a style rule, and CA means a code-quality analyzer rule such as 'mark members as static'.
  2. 2. A method returns string? and you write result.Length without checking. What does the compiler report?

    With nullable reference types enabled, dereferencing a value that may be null gives warning CS8602 (an error only if you configure warnings as errors).
  3. 3. Which setting makes only the nullable warnings fail the build, leaving other warnings alone?

    WarningsAsErrors accepts specific IDs or the nullable shorthand. TreatWarningsAsErrors affects all warnings, and NoWarn hides them.
  4. 4. In .editorconfig, which setting wins when these all apply to the same rule: dotnet_diagnostic.IDE0005.severity, a category setting and dotnet_analyzer_diagnostic.severity?

    More specific settings beat broader ones: the individual rule overrides the category, which overrides the global default.
  5. 5. What is the best way to handle a warning you believe is a false positive?

    A narrow, documented suppression keeps the rule active everywhere else and tells future readers why the exception exists.

Summary

  • The compiler and analyzers report diagnostics with an ID (CS, CA, IDE, ...), a message, a location and a severity (error, warning, suggestion, silent, none).
  • Treat warnings as questions: unused variables, unreachable code, non-exhaustive switches, async without await and un-awaited calls usually mark real mistakes.
  • Nullable warnings (CS8600 to CS8625) predict NullReferenceException; fix them with checks, ?./??, [NotNullWhen], required members or an explicit exception, and use ! sparingly.
  • Built-in analyzers ship with the SDK (AnalysisLevel, EnforceCodeStyleInBuild); extra analyzers come as NuGet packages with PrivateAssets="all".
  • .editorconfig stores style, naming and severity rules; specific settings override broad ones, and subfolders can override the root.
  • TreatWarningsAsErrors or WarningsAsErrors makes warnings fail the build; adopt them gradually in old code.
  • Suppress narrowly (#pragma, #nullable, [SuppressMessage], .editorconfig) and always explain why. Use dotnet format --verify-no-changes in CI.

Next: Design Patterns in C#