Nullable reference analysis
Nullable reference analysis
string? tells the compiler that a reference may be absent. string expresses an expectation that it is not null. With nullable analysis enabled, C# tracks assignments and branches and warns about operations that might dereference null. These annotations do not create different CLR reference types or insert automatic runtime guards. In contrast, int? is the value type Nullable<int>, which can represent an integer or no value.
Use <Nullable>enable</Nullable> in the project (as in the shared fixture), or #nullable enable in a file. Decide whether absence is valid at each boundary: return an optional result for a missing lookup, reject invalid required arguments, or substitute a documented default. Empty text is not the same as absent text.
using System;string? title = FindTitle(2);if (title is null) Console.WriteLine("Missing title");else Console.WriteLine(title.Length);Console.WriteLine(FindTitle(1)?.Length ?? 0);static string? FindTitle(int id) => id == 1 ? "Atlas" : null;After the null test, the else branch has a non-null title. The second expression returns the length for a present title and zero for an absent one. That fallback deliberately treats absence like an empty title; choose it only if the caller needs that policy.
Expected output (reasoned, not executed):
Missing title5Communicate a conditional null contract
using System;using System.Diagnostics.CodeAnalysis;if (HasTitle("Atlas", out var title)) Console.WriteLine(title.Length);if (!HasTitle("", out _)) Console.WriteLine("Rejected empty title");static bool HasTitle(string input, [NotNullWhen(true)] out string? title){ title = string.IsNullOrWhiteSpace(input) ? null : input; return title is not null;}The attribute tells nullable flow analysis that a true result guarantees a non-null output. The implementation must actually honor that promise. Attributes describe contracts; they are not validation code.
Expected output (reasoned, not executed):
5Rejected empty titleSee why null-forgiving is not a guard
using System;string? missing = null;try{ Console.WriteLine(missing!.Length);}catch (NullReferenceException){ Console.WriteLine("Still null at runtime");}This intentionally demonstrates a bad assumption in a contained program. The postfix ! suppresses nullable warnings for the expression but does not change its runtime value. The exception is caught only to demonstrate the outcome; use a guard instead in ordinary code.
Expected output (reasoned, not executed):
Still null at runtimeCommon mistakes and edge cases
A non-nullable array element can initially be null before assignment. Constructors, deserialization, legacy code and incorrect annotations can also violate intended contracts. Do not equate zero warnings with absence of runtime nulls. CS8602 is a possible-null dereference warning; its severity can be raised to an error by project settings. In the separate diagnostic fixture, remove ! and inspect the warning rather than executing the invalid dereference. A null-forgiving operator is justified only by an independently established invariant the compiler cannot see.
Practice and next steps
Write DisplayName(string? name) to return "Guest" for null or whitespace and otherwise return the trimmed name. Test null, " ", " Ada ", and "A". Do not use !.
Next: Type, property and relational patterns.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nullable reference analysis — knowledge check
Apply the lesson concepts to the following scenarios.
What does string? change when nullable analysis is enabled?
What does title! do if title is null?
Which branch makes title safe to dereference after `if (title is null) return;`?
What does NotNullWhen(true) on an out parameter promise?
How is int? different from string?