skip to content

With nullable reference types enabled, how does C# flow analysis decide whether a dereference earns warning CS8602, and where can it be fooled?

level: middleimportance: should knowfreq 45%

answer

  1. not-null or maybe-null
  2. assignments and checks move the state
  3. signatures, never method bodies
  4. a method call resets nothing

basics

~20 s

The compiler tracks each expression as not-null or maybe-null: declarations set the start, assignments and null checks change it, and CS8602 fires on dereferencing a maybe-null value. It reads only signatures, so helpers and method calls that change fields go unseen.

solid answer

~40 s

Null-state analysis is a flow analysis inside one method body. A non-nullable declaration starts **not-null**, a nullable one **maybe-null**; an assignment copies the state of its right-hand side, checks such as `is null`, `is not null`, `!= null` or a property pattern narrow it on each branch, and `??=` leaves it not-null, including after an early `return` or `throw`. Dereferencing a maybe-null expression warns CS8602, and afterwards the compiler treats it as not-null to avoid repeat warnings. It tracks member paths such as `ticket.Email` as well as locals. It is deliberately optimistic: it never looks inside called methods, so a helper that checks for null does not narrow anything without nullability attributes, and a call that sets `ticket.Email` back to null does not reset the narrowed state, so the code compiles clean and throws.

code

csharp · 20 lines
csharp
var ticket = new Ticket { Email = "[email protected]" };
if (ticket.Email is not null)
{
    ticket.Clear();                              // sets Email to null
    try { Console.WriteLine(ticket.Email.Length); } // no warning
    catch (NullReferenceException) { Console.WriteLine("NullReferenceException"); }
}

string? note = Lookup(1);
Action print = () => Console.WriteLine(note.Length); // CS8602: state at the lambda
if (note is null) return;
Console.WriteLine(note.Length);                      // narrowed: no warning

static string? Lookup(int id) => id > 0 ? "refund" : null;

class Ticket
{
    public string? Email { get; set; }
    public void Clear() => Email = null;
}

go deeper

for a junior

Recall the two states, not-null and maybe-null, and that a null check or an assignment of a non-null value removes CS8602.

for a middle

Explain how declarations set the starting state, how assignments, checks and early exits move it, and why one bad dereference warns only once.

for a senior

Name the blind spots: helpers whose bodies are unread, member paths not reset by method calls, lambdas, other threads and oblivious libraries, and the local-copy fix.

for a principal

Set expectations for a team: a clean nullable build is evidence, not proof, so boundary validation and attribute-annotated helpers still matter in review.

## Null-state: the thing being tracked With the warning flag of the nullable context on, the compiler gives every reference expression a **null-state** at every point in a method: **not-null** or **maybe-null**. Warnings appear where that state contradicts what the code does with the value: - **CS8602**, *Dereference of a possibly null reference.*, when you call a method, read a member or index into a maybe-null expression. - **CS8600** and **CS8601**, when a maybe-null value is assigned to something declared non-nullable. - **CS8603** and **CS8604**, when a maybe-null value is returned from, or passed as an argument to, something declared non-nullable. The declared type sets the **starting** state: a non-nullable parameter, field or property starts not-null, a nullable one starts maybe-null, and a value from nullable-oblivious code (compiled with nullable disabled) is treated as not-null. ## What moves the state Within a method body, the analysis follows control flow the way definite assignment does: 1. **Assignments.** After `x = expr`, `x` has the state of `expr`. A string literal or `new` is not-null; `null`, a `string?`-returning call or a cast to `string?` is maybe-null. 2. **Null checks.** `x is null`, `x is not null`, `x == null`, `x != null` and a property pattern such as `x is { Length: > 0 }` all narrow `x` on the branch where the answer is known; `x ??= fallback` leaves `x` not-null, and `x ?? fallback` is not-null as a whole when the fallback is. 3. **Exits.** After `if (x is null) return;` or `throw`, the rest of the method sees `x` as not-null. 4. **Dereferences.** After `x.Length`, even one that warned, `x` is treated as not-null, because execution only continues past it if `x` was not null. This keeps one mistake from producing a cascade of warnings. 5. **Member paths.** A check on `ticket.Email` narrows `ticket.Email` itself, not just locals, until something assigns it. `var` locals are declared with the nullable form of the inferred type, so `var name = "Ada"; name = null;` is accepted; the state still follows the assignments. ## Where it is blind The analysis is deliberately **local and optimistic**. It looks at signatures, never bodies: | Situation | What the compiler concludes | Reality | |---|---|---| | `if (IsValid(order)) order.Note.Length` where `IsValid` checks `Note` | still maybe-null, CS8602 | false positive | | `if (t.Email is not null) { t.Clear(); t.Email.Length }` where `Clear` sets `Email = null` | still not-null, no warning | `NullReferenceException` | | A lambda created before a null check | the state where the lambda is written | warns even if the call happens after the check | | A value from an oblivious library method | not-null, no warning | whatever the library returns | The first row is fixed by describing the helper's contract with nullability attributes such as `[NotNullWhen(true)]`, the subject of the lesson on flow analysis attributes; nothing in this leaf makes the compiler read a method body. The second row is the trade-off the design makes: the compiler does not reset member state on calls, which keeps ordinary code from drowning in warnings at the cost of missing a real null. Concurrency is invisible too: another thread can null a field between your check and your use. ## Reading the warnings well - A CS8602 on a local almost always means a real missing check or a wrong declaration. - A CS8602 right after a call to your own validation helper means the helper's signature does not tell the compiler what its body proves. - **No** warning on a member path after a method call is not proof of safety. Copy the member into a local after the check (`var email = t.Email; if (email is null) return;`) and the local cannot be changed behind your back. - In a loop, the state at the top of the body merges every path into it, so a variable set to null at the end of one iteration is maybe-null at the start of the next. - When a warning appears far from where the null came from, follow the assignments backwards: the state at each point is the state of the last assignment or check on that path. - A clean build with nullable enabled says "no path the analysis can see dereferences a maybe-null value", which is less than "this code never throws `NullReferenceException`". The compiler's docs put it plainly: the analysis cannot make assumptions about the semantics of methods or properties; it applies the language's rules for null checks and assignments, and attributes on APIs supply the rest.

  • How do you make a null check inside your own helper method count at the call site?
    Describe the contract in the helper's signature with a nullability attribute, for example `[NotNullWhen(true)]` on the parameter of a bool-returning check. The compiler never reads the helper's body, only its signature and attributes; those attributes are covered with flow analysis attributes.
  • Why does a second dereference of the same maybe-null local not warn again?
    After a dereference the compiler sets the variable's state to not-null, because execution only gets past that line when the value was not null. Only the first dereference warns, so one missing check produces one CS8602 rather than a cascade.

  • The compiler reads a helper method's body to see its null checks.
  • Any method call resets the null-state of every member.
  • A clean nullable build proves the code cannot throw NullReferenceException.
  • Only locals are tracked, never properties like order.Customer.
  • A null check in a lambda's caller narrows the variable inside it.