Skip to content
Latchkey

C# warning treated as error (TreatWarningsAsErrors) in CI

A C# compiler warning is being promoted to an error because TreatWarningsAsErrors is on. The build fails on code that only warns locally, where the same project may not enforce warnings as errors.

What this error means

dotnet build fails on a warning such as "error CS8602: Dereference of a possibly null reference" or "warning CS0168 ... treated as an error", because warnings are errors in this configuration.

dotnet
Service.cs(42,13): error CS8602: Dereference of a possibly null reference. [/app/MyApp.csproj]
# (TreatWarningsAsErrors is enabled, so the CS8602 warning fails the build)

Common causes

TreatWarningsAsErrors is enabled

The project or a Directory.Build.props sets <TreatWarningsAsErrors>true</TreatWarningsAsErrors>, so any warning fails the build.

A new analyzer or nullable warning appeared

Enabling nullable reference types or a new analyzer surfaces warnings that now block the build.

How to fix it

Fix the underlying warning

  1. Read the warning code and message at the reported file and line.
  2. Resolve it (add a null check, remove the unused variable).
  3. Re-run the build so no warning remains to promote.
Service.cs
if (user is not null)
{
    Use(user.Name);
}

Scope warnings-as-errors deliberately

Keep it on but exempt specific codes you have triaged with WarningsNotAsErrors, rather than disabling it wholesale.

Directory.Build.props
<PropertyGroup>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  <WarningsNotAsErrors>CS0168</WarningsNotAsErrors>
</PropertyGroup>

How to prevent it

  • Enforce warnings as errors locally too, so they never surprise CI.
  • Fix warnings as they appear instead of suppressing broadly.
  • Use WarningsNotAsErrors for triaged exceptions only.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →