A nullable warning should be able to stop a CI build before an unsafe dereference ships. An SDK analyzer can catch a different mistake in the same build: rethrowing an exception in a way that discards part of its stack trace. This tutorial makes both checks fail, repairs the code, and then checks the corrected program’s behavior.
The examples were verified on November 8, 2026 with .NET SDK 10.0.402, targeting net10.0, in an offline container. The programs use ordinary C# top-level statements and BCL APIs, with no third-party packages or test framework.
Give the build an explicit warning policy
Create an empty folder containing Example.csproj with the following contents. Save exactly one of the programs below as Program.cs at a time; keeping both in the project would introduce unrelated duplicate declarations.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
</Project>
Nullable enables nullable-reference analysis. TreatWarningsAsErrors makes reported compiler and analyzer warnings fail this compilation. It does not turn on every available rule. The SDK includes code-quality analyzers, enabled by default for projects targeting .NET 5 and later; this .NET 10 project uses that default. See Microsoft’s code-analysis overview.
This policy is suitable for a small project with a clean warning baseline. For an existing application, first inspect its warnings and agree which rules to enforce. Microsoft’s warning options reference also documents WarningsAsErrors, including the nullable group for a narrower rollout. The project above deliberately uses the broader policy.
Make the build reject two different defects
Save this complete negative example as Program.cs. It is intentionally expected to fail compilation under the project settings above.
using System;
static int NameLength(string? name) => name.Length;
static void Relay(Action operation)
{
try
{
operation();
}
catch (InvalidOperationException ex)
{
throw ex;
}
}
Console.WriteLine(NameLength(null));
Relay(() => throw new InvalidOperationException("sample"));
Run the build from the project folder:
dotnet build Example.csproj --nologo --verbosity quiet
The verified build exited with code 1, produced no application stdout, and reported both diagnostic IDs. These are the relevant lines from the compiler log:
/tmp/app/Program.cs(3,40): error CS8602: Dereference of a possibly null reference. [/tmp/app/Example.csproj]
/tmp/app/Program.cs(13,9): error CA2200: Re-throwing caught exception changes stack information (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2200) [/tmp/app/Example.csproj]
CS8602 identifies the unchecked access to a possibly null reference. CA2200 identifies the explicit rethrow of the caught exception. Microsoft documents CA2200 as a warning enabled by default in .NET 10: naming the exception in a rethrow restarts its stack trace at that method. Use a bare rethrow inside the handler to retain the original stack information. See the CA2200 rule and fix.
Repair the code and assert the intended behavior
Replace all of Program.cs with this complete program. The length function gives null a defined result of zero; empty text also has length zero, while whitespace remains ordinary text. The relay keeps the original exception and propagates it to its caller.
using System;
static int NameLength(string? name) => name is null ? 0 : name.Length;
static void Relay(Action operation)
{
try
{
operation();
}
catch (InvalidOperationException)
{
throw;
}
}
static void CheckLength(string? name, int expected, string label)
{
int actual = NameLength(name);
if (actual != expected)
throw new InvalidOperationException($"{label}: expected {expected}, got {actual}");
Console.WriteLine($"{label}: {actual}");
}
CheckLength("Ada", 3, "name");
CheckLength(null, 0, "null");
CheckLength("", 0, "empty");
CheckLength(" ", 2, "spaces");
var original = new InvalidOperationException("sample");
bool caught = false;
try
{
Relay(() => throw original);
}
catch (InvalidOperationException actual)
{
if (!ReferenceEquals(actual, original))
throw new InvalidOperationException("Relay replaced the exception.");
caught = true;
}
if (!caught)
throw new InvalidOperationException("Relay swallowed the exception.");
Console.WriteLine("same exception propagated");
Build again, then run the assembly only if the build succeeds:
dotnet build Example.csproj --nologo --verbosity quiet
dotnet bin/Debug/net10.0/Example.dll
The corrected fixture built with zero compiler/analyzer warnings and zero errors, exited successfully, and matched this stdout exactly:
name: 3
null: 0
empty: 0
spaces: 2
same exception propagated
The assertions throw if a length changes, if the relay replaces the exception, or if it swallows it. A failure therefore prevents the final success line. These deterministic checks need no files, network, timing assumptions, or cleanup. The two fixtures were built in separate temporary projects.
Put the same checks on the CI path
Use the same SDK version on developer machines and the CI runner. Commit the project settings with the code. Configure a required build step using the build command above, and configure the assembly run as a subsequent step that executes only after a successful build. Make a nonzero exit code fail the job in both steps. Keep the negative example in a separate disposable project when checking the gate; commit the corrected program to the working example.
If your CI build unexpectedly accepts the negative program, inspect the diagnostic IDs before adding more tooling. Check that it builds the intended project, that nullable analysis and warnings-as-errors are effective, and that repository settings have not disabled SDK analyzers or suppressed these diagnostics. An editor suggestion alone does not establish build enforcement: code-style analysis on command-line builds is disabled by default, as the analysis overview explains.
TreatWarningsAsErrors applies to C# compilation. It is distinct from MSBuild’s -warnaserror switch, which affects warnings from other build tasks too; Microsoft’s warning options reference explains that distinction. Neither setting enables suppressed or disabled diagnostics.
Understand what a green result proves
The rejected fixture proves that these two diagnostics stop this build under the recorded settings. The corrected fixture proves the four selected length results and propagation of the same exception instance. Its runtime assertions do not inspect stack-trace contents; the stack-preservation explanation comes from the CA2200 documentation. A clean build does not prove the absence of all null failures or all application defects, and these console checks are not an integration test of your CI provider.
For related language behavior, continue with null-coalescing operators and fallback values or required members and construction guarantees. Keep those API design decisions separate from the build policy that enforces diagnostics.