Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 182 ยท Null Safety and Errors

Null-Handling Operators

Master C# null-handling operators - null-conditional ?. and ?[], null-coalescing ?? and ??=, is null patterns, C# 14 null-conditional assignment, ThrowIfNull and the null object pattern.

Once you accept that some references may be null (see Nullable Reference Types), you need a vocabulary for dealing with them. Writing if (x != null) around every access works but buries the logic. C# has a small family of operators for the common situations: call this only if it exists, use a fallback if it is missing, assign only if empty, and test for null reliably.

This lesson covers each operator, what it really does at runtime (including the subtle short-circuiting rules), the C# 14 addition that lets you assign through ?., the guard-clause helpers, and finally a design pattern that removes many null checks altogether.

The null-conditional operator ?.

a?.b evaluates a; if a is null the whole expression is null, otherwise it is a.b. The same works for method calls and for indexers with ?[ ].

C# ?. and ?[] stop at null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two points to notice. First, the result type becomes nullable: name?.Length is int?, because the answer might be "nothing". Second, it short-circuits the entire chain: in a?.b.c.d if a is null, .b.c.d is skipped, not just .b. You do not need ?. at every step unless a later link can also be null.

C# Short-circuiting skips the rest of the chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line proves something many developers miss: when the receiver is null, the arguments of the call are not evaluated either, so a side effect like logging will not happen.

Invoking delegates and events

A classic use is raising an event or calling a callback that might not be set. handler?.Invoke(args) is thread-safe in a way that if (handler != null) handler(args) is not, because the delegate is read once:

C# Safe callback invocation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The null-coalescing operator ??

a ?? b gives a if it is not null, and b otherwise. The right side is evaluated only when needed. It is the natural partner of ?.: one produces a maybe-null value, the other supplies the default.

C# Fallbacks with ?? (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line of the example throws. The right side of ?? may be a throw expression, a compact way to say "this must exist or the program cannot continue". The run prints the first three lines and then ends with Unhandled exception. System.InvalidOperationException: name is required.

The null-coalescing assignment ??=

a ??= b means "if a is null, assign b to it". It is a lazy initializer in one line, and b is not evaluated when a already has a value.

C# Lazy initialization and a tiny cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

??= is not thread-safe for shared state (two threads may both see null and both initialize). For lazy singletons use Lazy<T> or a lock.

Testing for null: is null, is not null, ==

x == null calls the == operator, which a class can overload and make lie. x is null is a pattern test that can never be overloaded, so it always asks the real question. Most style guides prefer the pattern forms.

C# == can be overloaded, is null cannot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Also remember that a type test such as o is string is false for null, so it doubles as a null check.

Null-conditional assignment (C# 14)

Before C# 14 you could read through ?. but not write. Assigning customer?.Name = "x" was an error. C# 14 (.NET 10) allows it: the assignment, and the evaluation of the right-hand side, happen only when the receiver is not null. Compound assignments such as += and ++ are also allowed.

C# customer?.Name = value (C# 14)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Nothing printed "evaluating never runs", confirming the short circuit. Two limits: the increment operators ++ and -- are not allowed with ?. on the left, and the result of the assignment expression is not usable as a value. If you use an older language version, write an if (x is not null) { x.Name = ...; } block instead.

Guard clauses: ThrowIfNull and friends

Public methods should reject bad arguments at the door. The BCL provides static helpers (the ThrowIf family) so the check is one readable line:

C# Guard clauses with ThrowIf helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ThrowIfNull (since .NET 6) captures the argument's expression automatically (CallerArgumentExpression), which is why the message names name without you typing it. Even with nullable annotations on, guard public methods: callers in oblivious code or via reflection can still pass null. The details of exceptions are in Exceptions.

The null object pattern

Sometimes the cleanest way to handle null is to make "nothing" a real object that does nothing. Instead of returning null for "no logger" and forcing every caller to check, return a logger whose methods are empty.

C# A null object removes the checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Service never mentions null. The Microsoft logging abstractions use the same idea (NullLogger). Related designs: return an empty collection instead of null (callers can then loop without a check), return string.Empty, or use Option-like results with TryParse shapes (see Exception Filters and Error Handling Patterns).

Never return null for a collection or array. An empty list is the right "nothing" there, and callers will otherwise forget a check sooner or later.

Choosing the right tool

Situation Tool
Call or read only if present x?.Member, x?[i]
Fallback value x ?? fallback
Fail when missing x ?? throw ... or ThrowIfNull(x)
Initialize once x ??= new() (single-threaded)
Reliable test x is null, x is not null
Write only if present x?.Prop = value (C# 14)
Remove the checks null object, empty collections

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. If customer is null, what does customer?.Address.City evaluate to?

    ?. short-circuits the whole rest of the member chain, so the result is null (typed as a nullable City type) and nothing after it runs.
  2. 2. What is the type of the expression name?.Length when name is a string?

    The expression may produce nothing, so the int result is lifted to the nullable value type int?.
  3. 3. Why is x is null preferred over x == null?

    A class can overload ==, so == null might not mean what it says. is null is a pattern test the type cannot change.
  4. 4. In C# 14, what happens with absent?.Name = Describe("x") when absent is null?

    Null-conditional assignment short-circuits both the assignment and the evaluation of the right-hand side.
  5. 5. What does list ??= [] do when list already holds a list?

    ??= assigns only when the left side is null, so an existing value is kept and the right side is never evaluated.

Summary

  • ?. and ?[] access a member only when the receiver is not null; they short-circuit the whole chain and make the result nullable.
  • ?? supplies a fallback (or a throw); ??= assigns only if the target is null.
  • Prefer is null / is not null over == null, since == can be overloaded.
  • C# 14 allows x?.Member = value and compound assignments; the right side runs only when x is not null.
  • Guard public methods with ArgumentNullException.ThrowIfNull and the other ThrowIf helpers.
  • The null object pattern and empty collections remove many null checks entirely.

Next: Exceptions