Skip to content

1.16 — Null-Handling Operators

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.15 Nullability · Next: 1.17 Pattern matching

Markers: — · Confidence: 🔴 · Last reviewed: —


TL;DR

  • ?? — "use this instead if the left side is null".
  • ?. — "only carry on if this is not null, otherwise give me null".
  • ??= — "assign this only if the variable is currently null".
  • A chain of ?. stops at the first null and returns null for the whole expression.

The concept

These four operators exist to replace long, noisy null checks with short ones. That is their whole purpose — they add no new capability, just less typing and less clutter.

Before them, guarding against null looked like this:

string city;
if (order != null && order.Customer != null && order.Customer.Address != null)
    city = order.Customer.Address.City;
else
    city = "Unknown";

After:

string city = order?.Customer?.Address?.City ?? "Unknown";

Same behaviour, one line, and much easier to read once the symbols are familiar.


How it works

?? — null-coalescing

"If the left side is null, use the right side instead."

string? name = null;
string display = name ?? "Anonymous";      // "Anonymous"

string? found = "Ada";
string display2 = found ?? "Anonymous";    // "Ada"

It only triggers on null, not on empty or zero:

string empty = "";
string result = empty ?? "fallback";       // "" — empty string is NOT null
int zero = 0;
int? maybe = 0;
int r = maybe ?? 99;                       // 0 — zero is a real value

You can chain it. It uses the first non-null it finds:

var value = fromCache ?? fromDatabase ?? fromDefault ?? "last resort";

It is also short-circuiting — if the left side is not null, the right side is never evaluated:

var config = cached ?? LoadFromDisk();
// LoadFromDisk() only runs if 'cached' is null. No wasted work.

?. — null-conditional

"If this is null, stop and give back null. Otherwise carry on."

string? name = null;
int? length = name?.Length;      // null — Length was never called

string? real = "Ada";
int? length2 = real?.Length;     // 3

Two things to notice:

The result becomes nullable. name.Length would be an int, but name?.Length is an int?, because it now has a way to produce "no answer".

A chain stops at the first null. It does not keep going and crash:

order?.Customer?.Address?.City
// If 'order' is null → the whole thing is null.
// Customer, Address and City are never touched.

There is also an indexer version:

var first = list?[0];            // null if list is null

And it works for method calls, which is how you safely raise events:

OrderCompleted?.Invoke(this, args);   // does nothing if nobody subscribed

See 1.12 for why this specific use also avoids a race condition.

??= — null-coalescing assignment

"Assign this only if the variable is currently null."

string? name = null;
name ??= "Default";        // name is now "Default"
name ??= "Something else"; // no effect — name is not null any more

Which is shorthand for:

if (name is null)
    name = "Default";

It is very handy for lazy initialisation:

private List<string>? _items;
public List<string> Items => _items ??= LoadItems();
// LoadItems() runs on the first access only.
// Note: this is NOT thread-safe. Use Lazy<T> if several threads may hit it.

The one that catches people out

int? count = list?.Count ?? 0;

Read the precedence carefully: ?. binds tighter than ??. So this is (list?.Count) ?? 0 — if list is null the whole list?.Count is null, and then ?? supplies 0. That is what you want.

But this is different:

var length = person?.Name.Length;
// If person is null → null, fine.
// If person is NOT null but Name IS null → NullReferenceException!
// The ?. only guarded 'person', not 'Name'.

Every link in the chain needs its own ?.:

var length = person?.Name?.Length;   // now both are guarded

Code

Realistic before-and-after:

// BEFORE — correct, but hard to read
public string GetShippingCity(Order order)
{
    if (order == null) return "Unknown";
    if (order.Customer == null) return "Unknown";
    if (order.Customer.ShippingAddress == null) return "Unknown";
    if (string.IsNullOrEmpty(order.Customer.ShippingAddress.City)) return "Unknown";
    return order.Customer.ShippingAddress.City;
}

// AFTER — same behaviour
public string GetShippingCity(Order? order)
{
    var city = order?.Customer?.ShippingAddress?.City;
    return string.IsNullOrEmpty(city) ? "Unknown" : city;
}

Note that ?? alone would not be enough here, because an empty string is not null. The requirement was "unknown if missing or blank", so it still needs an explicit check. This is a very common mistake — reaching for ?? when you actually need string.IsNullOrWhiteSpace.


Interview questions

Q: What is the difference between ?? and ?.?

?? supplies a fallback value when the left side is null — name ?? "Anonymous" gives you the name, or "Anonymous" if it is null. ?. stops a member access when the thing on the left is null and returns null for the whole expression instead of throwing. So ?? is about supplying a default, and ?. is about safely skipping. They are usually used together: order?.Customer?.Name ?? "Unknown".

Q: Does ?? treat an empty string as null?

No. It only checks for null. An empty string, a zero, and false are all real values and pass straight through. That trips people up when they use ?? for what is really a "is this missing or blank" check — for strings you usually want string.IsNullOrWhiteSpace instead.

Q: What happens in a long ?. chain if something in the middle is null?

The whole expression short-circuits and evaluates to null. Nothing after the null link is evaluated at all. But every link needs its own ?. — writing a?.B.C only protects against a being null, so if B turns out to be null you still get a NullReferenceException. You need a?.B?.C.

Q: Where is ??= useful?

Lazy initialisation, mainly — _cache ??= BuildCache() runs the expensive work only on first access. It is worth remembering that it is not thread-safe, so if several threads could hit it at once you want Lazy<T> instead.


Traps ⚠️

  • ?? only checks null. Empty string, 0 and false all pass through as valid values.
  • Every link in a chain needs its own ?.. a?.B.C does not protect B.
  • ?. makes the result nullable. int becomes int?, which can cause a surprising compile error further along.
  • ??= is not thread-safe. Two threads can both see null and both assign. Use Lazy<T> for that.
  • ?. can hide real bugs. If something should never be null, silently returning null turns a loud crash into a quiet wrong answer that shows up much later.
  • ?. does not work with await directly. await task?.RunAsync() fails, because you cannot await a null Task. You need an explicit check.


Sources