Roslyn Nullability Flow Analysis & NRT Annotations
1Concept
Nullable Reference Types (NRT) transform `NullReferenceException` from a runtime disaster into a compile-time warning. Roslyn tracks state transitions across branches and method calls via dataflow analysis.
2Architecture Diagram
string? maybeNull = GetName();
│
if (maybeNull != null)
│
▼
[ Flow State: NotNull ] ──> maybeNull.ToUpper() is 100% Safe (Zero Compiler Warnings)3Code Example
C# 13 & .NET 9
using System;
public class NullSafetyDemo
{
public static string FormatUsername(string? rawInput)
{
// Roslyn detects rawInput might be null
if (string.IsNullOrWhiteSpace(rawInput))
{
return "Anonymous_User";
}
// Roslyn knows rawInput is NOT null here
return rawInput.Trim().ToUpperInvariant();
}
public static void Main()
{
Console.WriteLine($"Formatted: {FormatUsername(" alex_dev ")}");
Console.WriteLine($"Formatted: {FormatUsername(null)}");
}
}4Expected Output
Formatted: ALEX_DEV Formatted: Anonymous_User
5Key Takeaways
- ✓Enable `<Nullable>enable</Nullable>` in all .csproj project files.
- ✓Treat compiler warnings as errors (`<TreatWarningsAsErrors>true</TreatWarningsAsErrors>`).
- ✓NRT is a static analysis tool that compiles to pure standard reference types.