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.
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
- Read the warning code and message at the reported file and line.
- Resolve it (add a null check, remove the unused variable).
- Re-run the build so no warning remains to promote.
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.
<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
WarningsNotAsErrorsfor triaged exceptions only.