Nullable Safety: The Safety Net

Nullable Safety: The Safety Net in C#: A warehouse where every box looks identical is a warehouse where you reach in blind.

The Analogy: The "May Be Empty" Label

A warehouse where every box looks identical is a warehouse where you reach in blind. Sometimes you get a component; sometimes your hand closes on nothing and the line stops. The fix costs nothing: print MAY BE EMPTY on the boxes that can arrive empty, and leave the rest unmarked. Now the label tells you when to shake the box first, and a supervisor walking the aisle can spot an unlabelled box being handled carelessly.

That is nullable reference types. Since C# 8 the type string means "there is a string here" and string? means "there may be nothing here". The compiler reads those labels, traces where values flow, and warns you the moment you reach into an unshaken box.

This matters because NullReferenceException is the single most common crash in .NET history — Tony Hoare called the null reference his "billion-dollar mistake". C# cannot remove null, but it can make the possibility of null part of the type you write down, which turns a 3 a.m. production page into a squiggly line at 3 p.m.


Syntax or Core Structure

#nullable enable
using System;

class Program
{
    // '?' on the parameter says null is a legitimate argument.
    static int Length(string? text) => text?.Length ?? -1;

    static void Main()
    {
        string sure = "hello";      // no '?': the compiler will not let this be null
        string? maybe = null;       // '?': null is expected here

        Console.WriteLine($"sure: {sure.Length}");
        Console.WriteLine($"maybe length: {Length(maybe)}, {Length("abcd")}");

        string label = maybe ?? "(none)";     // null-coalescing: a fallback value
        Console.WriteLine($"label: {label}");

        maybe ??= "filled in";                 // assign only if currently null
        Console.WriteLine($"maybe now: {maybe}");

        int? count = null;                     // nullable VALUE type: Nullable<int>
        Console.WriteLine($"count has value: {count.HasValue}, or default {count.GetValueOrDefault(7)}");
        count = 3;
        Console.WriteLine($"count: {count.Value}, doubled {count * 2}");

        int?[] readings = { 4, null, 9, null, 2 };
        int total = 0, missing = 0;
        foreach (int? r in readings)
        {
            if (r is int value) total += value;   // pattern unwraps and tests in one step
            else missing++;
        }
        Console.WriteLine($"total {total} from {readings.Length - missing} readings, {missing} missing");

        string?[] names = { "ada", null, "grace" };
        foreach (string? n in names)
            Console.WriteLine($"  {n?.ToUpper() ?? "??"} ({n?.Length.ToString() ?? "-"})");
    }
}

Output:

sure: 5
maybe length: -1, 4
label: (none)
maybe now: filled in
count has value: False, or default 7
count: 3, doubled 6
total 15 from 3 readings, 2 missing
  ADA (3)
  ?? (-)
  GRACE (5)

Three operators carry most of the weight. ?. says "if the left side is null, stop and produce null"; ?? supplies a value when the left side is null; ??= fills a hole in place. Together they collapse the classic four-line null check into one expression — text?.Length ?? -1.

Note that n?.Length has type int?, not int: null-conditional access always widens the result so it has somewhere to put "nothing".


Technical Depth: What the Compiler Actually Knows

Two completely different features share one ?

Featureint? (value type)string? (reference type)
What it isNullable<int>, a real structthe same string, plus an annotation
Exists at run timeyes — a struct with HasValue and Valueno — attributes in metadata only
SinceC# 2.0C# 8.0
Ignoring itimpossible — the types differpossible — it is only a warning
Costs memoryyes, one extra bool per valuenothing

That second column is the crucial one: nullable reference types change no generated code at all. string and string? are the same type to the runtime. Cast through object, deserialise JSON, load an entity, or call a library compiled without the feature, and a null can land in a variable the compiler swore was safe. The feature is a static analyser you cannot switch off per-expression, not a runtime guarantee.

Turning it on

<PropertyGroup>
  <Nullable>enable</Nullable>
  <WarningsAsErrors>nullable</WarningsAsErrors>
</PropertyGroup>

New projects from the .NET 6 templates onward have the first line already. In an existing codebase, enable it per file with #nullable enable at the top and work through the list — a ratchet, one file per pull request, beats a 4,000-warning big bang. #nullable disable warnings silences without changing the annotations, useful for generated code.

The second line is the one people skip and later regret. A nullable warning in a build log that already has two hundred warnings is invisible; as an error it gets fixed the day it appears.

The warnings worth recognising

CodeMeansTypical fix
CS8602dereference of a possibly-null valuecheck first, or ?.
CS8604possibly-null argument to a non-nullable parametercheck at the call, or annotate the parameter
CS8603possibly-null return from a non-nullable return typereturn a fallback, or make the return type ?
CS8618non-nullable field/property never initialisedconstructor, required, or make it ?
CS8625null literal assigned to a non-nullable typeyou meant the type to be ?
CS8600converting null literal or possible null to non-nullableusually a bad cast

Flow analysis: the compiler follows your checks

Inside a method the analyser tracks a state per variable — not-null or maybe-null — and updates it at every branch:

void Handle(string? input)
{
    // input: maybe-null
    if (input is null) return;
    // input: not-null — no warning below
    Console.WriteLine(input.Length);

    input = Fetch();          // assignment resets the state to whatever Fetch() promises
}

It understands is null, is not null, == null, throw, return, assignment, and ??=. It does not follow your helper methods — unless you tell it how.

The attributes that teach it about your helpers

if (!string.IsNullOrEmpty(s)) Console.WriteLine(s.Length);   // no warning: annotated in the BCL
if (int.TryParse(text, out int n)) Console.WriteLine(n);      // same trick

Those work because the framework methods are annotated. Yours can be too, from System.Diagnostics.CodeAnalysis:

AttributeSays
[NotNullWhen(true)]this out/parameter is not null when the method returns true
[MaybeNullWhen(false)]it may be null when the method returns false
[NotNullIfNotNull(nameof(x))]the result is non-null whenever x was
[MemberNotNull(nameof(_field))]after this method runs, that field is set (for Initialise helpers)
[NotNull] / [MaybeNull]override the state on the way out
[AllowNull] / [DisallowNull]the setter accepts null though the getter never returns it

Writing a TryGetX without [NotNullWhen(true)] is the most common reason a codebase ends up sprinkled with !.

The null-forgiving operator is a promise, not a check

string name = FindUser(id)!.Name;    // "trust me, this is not null"

! emits no code. It removes the warning and nothing else; if you are wrong you get the same NullReferenceException you would have had before the feature existed. Every ! is a comment saying "I have reasoned about this" — so it belongs in test code, immediately after an assertion, or with a short comment explaining the invariant. Where you actually want a check, say so:

string name = FindUser(id) ?? throw new InvalidOperationException($"user {id} not found");

That fails at the right place with the right message, which is worth far more than a stack trace pointing at .Name.

CS8618 and the uninitialised property

class Order
{
    public string Id { get; set; }              // CS8618: never initialised
    public string? Note { get; set; }            // fine: nullable by design
}

Four honest answers, in order of preference: make it required (public required string Id { get; set; } — the caller must set it, C# 11), set it in a constructor, give it a real default (= "";), or admit it is optional and write string?. The dishonest answer is = null!; — which is nevertheless the accepted convention for ORM entities where the framework sets the value by reflection. Use it there, with a comment, and nowhere else.

Lifted operators and three-valued logic

Nullable value types quietly change comparison:

int? a = null, b = 5;
Console.WriteLine(a < b);       // False
Console.WriteLine(a >= b);      // False  <- both are false!
Console.WriteLine(a == null);   // True
Console.WriteLine(a + b);       // (blank) - null, not 5

Any arithmetic touching null produces null, and any <, >, <=, >= involving null is false. So !(a < b) is not the same as a >= b any more, and if (a < b) ... else ... sends nulls down the else branch whether you thought about them or not. Equality is the exception: == and != behave sensibly, with two nulls equal.

Generics: T? means less than you think

For an unconstrained T, T? means "may be the default value", and default(T) is 0 for int, not null. That is why FirstOrDefault is annotated [MaybeNull] rather than returning T? — and why a "not found" result from a generic API is better expressed as bool TryGet(out T value) than as a nullable return.

The holes the analyser cannot see

string[] words = new string[3];       // three nulls, element type says non-nullable
Console.WriteLine(words[0].Length);   // no warning, throws at run time

Arrays of reference types start life full of nulls and the analyser does not track element states. The same blind spot covers deserialisation, reflection, Activator.CreateInstance, structs with reference-typed fields, and any dependency compiled before C# 8. Which leads to the one rule that survives all of this: validate at the boundary, trust inside.

public void Send(string to, Message message)
{
    ArgumentNullException.ThrowIfNull(to);          // .NET 6+, one line, names the parameter
    ArgumentNullException.ThrowIfNull(message);
    // everything below here can assume both are real
}

Public entry points, deserialised payloads and anything crossing a process edge get real run-time checks. Private methods downstream get annotations and nothing more.

Two nulls that mean different things

Phone = null can mean "this customer has no phone" or "we have not loaded the phone yet" — and code that confuses those ships bugs no compiler will catch. When the distinction matters, model it: a separate bool PhoneLoaded, a wrapper type, or splitting the loaded and unloaded shapes into two records. A single ? cannot carry two meanings.


Real World Example: A Boundary That Only Emits Valid Objects

Untrusted rows arrive from a CSV, a form post or a spreadsheet: every field may be missing, blank or nonsense. The pattern that pays for itself is a single gate — raw nullable input on one side, a fully-populated domain object on the other, and nothing in between that has to wonder whether Email is null.

#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

record Contact(string Name, string Email, string? Phone, int? Age)
{
    // Name and Email are non-nullable, so no checks are needed here at all.
    public string Display => Phone is null
        ? $"{Name} <{Email}>"
        : $"{Name} <{Email}> {Phone}";
}

class Program
{
    // NotNullWhen(true): callers get a non-null 'contact' without writing '!'.
    static bool TryCreate(
        IReadOnlyDictionary<string, string?> row,
        [NotNullWhen(true)] out Contact? contact,
        out string problem)
    {
        contact = null;
        problem = "";

        string? name = Get(row, "name");
        string? email = Get(row, "email");

        if (name is null) { problem = "name is required"; return false; }
        if (email is null) { problem = "email is required"; return false; }
        if (!email.Contains('@')) { problem = $"'{email}' is not an email"; return false; }

        int? age = null;
        string? rawAge = Get(row, "age");
        if (rawAge is not null)
        {
            if (!int.TryParse(rawAge, out int parsed))
            {
                problem = $"age '{rawAge}' is not a number";
                return false;
            }
            age = parsed;
        }

        contact = new Contact(name, email, Get(row, "phone"), age);
        return true;
    }

    // At this boundary a missing key, a null and a blank string all mean "absent".
    static string? Get(IReadOnlyDictionary<string, string?> row, string key) =>
        row.TryGetValue(key, out string? value) && !string.IsNullOrWhiteSpace(value)
            ? value.Trim()
            : null;

    static void Main()
    {
        List<Dictionary<string, string?>> rows = new()
        {
            new() { ["name"] = "Ada", ["email"] = "ada@example.com", ["phone"] = "555-0100", ["age"] = "36" },
            new() { ["name"] = " Grace ", ["email"] = "grace@example.com", ["age"] = null },
            new() { ["name"] = "Alan", ["email"] = "alan(at)example.com" },
            new() { ["email"] = "nobody@example.com" },
            new() { ["name"] = "Linus", ["email"] = "linus@example.com", ["age"] = "old" }
        };

        List<Contact> accepted = new();
        foreach (Dictionary<string, string?> row in rows)
        {
            if (TryCreate(row, out Contact? contact, out string problem))
            {
                accepted.Add(contact);        // no '!' required - the attribute did that work
                Console.WriteLine($"ok      {contact.Display}");
            }
            else
            {
                Console.WriteLine($"reject  {problem}");
            }
        }

        Console.WriteLine($"{accepted.Count}/{rows.Count} accepted");

        int? oldest = null;
        foreach (Contact c in accepted)
            if (c.Age is int age && (oldest is null || age > oldest)) oldest = age;

        Console.WriteLine($"oldest known age: {oldest?.ToString() ?? "unknown"}");
        Console.WriteLine($"with phone: {accepted.Count(c => c.Phone is not null)}");
    }
}

Output:

ok      Ada <ada@example.com> 555-0100
ok      Grace <grace@example.com>
reject  'alan(at)example.com' is not an email
reject  name is required
reject  age 'old' is not a number
2/5 accepted
oldest known age: 36
with phone: 1

Everything untrustworthy is confined to TryCreate. Past that gate, Contact.Display interpolates Name and Email with no defensive check — and the compiler will reject anyone who tries to construct a Contact without them. Phone and Age stay nullable because they genuinely are optional, and the ? on them is documentation every caller can see.

Two details worth copying. Get normalises three different flavours of "absent" into one, so the rest of the method has a single case to handle. And the guard c.Age is int age unwraps the nullable and tests it at once — cleaner than c.Age.HasValue && c.Age.Value > oldest, and it cannot throw.


Common Mistakes

  1. Reaching for ! to make the warning go away. It generates no check whatsoever. If you cannot explain in one sentence why the value cannot be null, you have not fixed the bug — you have hidden it. Use ?? throw when you want a guarantee.
  2. Believing the annotation is enforced at run time. string and string? are the same type to the CLR. JSON deserialisation, ORMs, reflection and pre-C#-8 libraries all hand out nulls the analyser never saw. Keep real checks at every public boundary.
  3. Making everything nullable to silence the build. A codebase where every type ends in ? carries all the noise of the feature and none of the benefit. The ? is information; spend it only where null is genuinely a valid value.
  4. Writing a TryGet without [NotNullWhen(true)]. Every caller then has to write value! on the success path, and each of those is a place where a future refactor can go wrong unnoticed.
  5. Assuming !(a < b) equals a >= b for nullables. With int? a = null, both comparisons are false. Any ordering logic over nullable numbers needs the null case handled explicitly before the comparison.
  6. Long ?. chains that hide a design problem. order?.Customer?.Address?.City?.Trim() returns null for four different reasons and tells you nothing about which one happened. That is usually a missing invariant somewhere upstream, not a formatting problem.
  7. Using = null!; as the default answer to CS8618. It is the right tool for ORM-populated entities and the wrong tool everywhere else. Prefer required, a constructor parameter, or an honest ?.
  8. Forgetting new string[10] is ten nulls. Arrays, and collections you Resize or preallocate, start out full of them with no warning at all. Fill them before exposing them, or type the element as nullable and be honest.

Best Practices

  • Enable <Nullable>enable</Nullable> on every new project, and add <WarningsAsErrors>nullable</WarningsAsErrors> so the warnings cannot rot.
  • Adopt it in legacy code file by file with #nullable enable, treating the warning list as a backlog rather than a blocker.
  • Validate at the edges with ArgumentNullException.ThrowIfNull, then trust your own types all the way down.
  • Annotate your Try* helpers so callers never need !; [NotNullWhen(true)] on the out parameter is almost always the right attribute.
  • Prefer ?? throw new ... with a message that names the missing thing over ! or a bare dereference.
  • Return empty collections, not null — Array.Empty<T>() or [] — so callers can foreach without a check.
  • Use is null and is not null in preference to == null: they ignore overloaded operators and feed the flow analyser.
  • When null carries two meanings, stop using null: split the type, add a flag, or use Try* so "absent" and "unknown" cannot be confused.

Practice Exercises

  1. Add #nullable enable to a scratch file and write a method static string Initials(string? first, string? last) that returns the uppercase initials of whichever names were supplied, "?" for a missing one. Use only ?., ?? and string interpolation — no if statements and no !.
  2. Write static bool TryFindByEmail(List<Contact> people, string? email, [NotNullWhen(true)] out Contact? found), then call it and use found.Display on the success path. Confirm the compiler raises no warning, and then remove the attribute to see the warning appear.
  3. Given int?[] temperatures = { 12, null, 15, null, null, 9 }; compute the count of readings present, their average as a double? that is null when nothing is present, and the highest reading — handling the all-null case without throwing. Print all three.
  4. Take a class with three string properties and no constructor, enable nullable, and resolve every CS8618 a different way: one with required, one through a constructor parameter, and one by deciding it is genuinely optional. Write one sentence per property explaining why that choice was the honest one.