skip to content

Coalescing and Conditional Access

?. and ?[] stop on null, ?? and ??= supply defaults, and C# 14 allows ?. on the left of an assignment. Interviewers ask about short-circuiting and the result types.

on this pageshow

explore

questions

5

In C#, what does `p?.Address?.City ?? "unknown"` evaluate to when `p` or its `Address` is null, and what does `?.` skip?

level: juniorimportance: must knowfreq 76%

answer

  1. one null test per operator
  2. the rest of the chain is skipped
  3. parentheses cut the chain
  4. ?? supplies the fallback

basics

~20 s

It evaluates to "unknown" in both cases. Each ?. tests the value on its left and, when that value is null, skips the rest of the access chain; ?? then replaces the null result with its right operand.

solid answer

~40 s

`?.` and `?[]` test only the operand on their left. If `p` is null, C# skips everything after it in the chain — `Address`, `City`, any method call and its arguments — and the chain's value is null. If `p` exists but `Address` is null, the second `?.` does the same. `??` then returns `"unknown"` because its left operand is null. The catch is that `?.` does not guard members further right: `p?.Address.City` throws `NullReferenceException` when `p` exists and `Address` is null, and wrapping part of the chain in parentheses, as in `(p?.Address).City`, ends the short-circuit. The operand of `?.` is evaluated only once.

code

csharp · 12 lines
csharp
var withAddress = new Profile("Ada", new Address("Leeds"));
var noAddress = new Profile("Bo", null);

Console.WriteLine(Line(withAddress));   // Ada from Leeds
Console.WriteLine(Line(noAddress));     // Bo from unknown
Console.WriteLine(Line(null));          // guest from unknown

static string Line(Profile? p) =>
    $"{p?.Name ?? "guest"} from {p?.Address?.City ?? "unknown"}";

record Address(string City);
record Profile(string Name, Address? Address);

go deeper

for a junior

Recall that ?. returns null instead of throwing when the value on its left is null, and that ?? supplies the fallback.

for a middle

Explain short-circuiting: one null skips the whole remaining chain, arguments included, and each ?. guards only its own left operand.

for a senior

Show where you place ?. by reading the model's real nullability, and spot the parenthesized chain or the missing ?. that still throws.

for a principal

Treat ?. placement as a statement about the data model; blanket ?. everywhere hides which members are truly optional.

## What `?.` and `?[]` do The **null-conditional operators** `?.` (member access) and `?[]` (element access) apply the access only when the operand on their left is not null. In C#: - if `a` is null, `a?.x` and `a?[i]` evaluate to null; - if `a` is not null, `a?.x` and `a?[i]` behave exactly like `a.x` and `a[i]`, including any exception that access throws (an out-of-range `a?[i]` on a real array still throws `IndexOutOfRangeException`); - the operand `a` is evaluated **once**, so it cannot change between the null test and the access. The **null-coalescing operator** `??` returns its left operand when that operand is not null and otherwise evaluates and returns its right operand. Paired with `?.`, it turns "maybe null" back into a usable value: `p?.Address?.City ?? "unknown"`. ## Short-circuiting covers the rest of the chain The C# documentation calls these operators **short-circuiting**: when one conditional access in a chain finds null, the rest of the chain does not execute. In `p?.Address.City.Length`, a null `p` means `Address`, `City` and `Length` are never touched, and the whole expression is null. The chain is the run of member accesses, element accesses and invocations that follow, so a method call such as `p?.Address.Format(Log())` skips the call **and** its argument `Log()`. What short-circuiting does **not** do is guard members further right. Each `?.` tests exactly one value: the one immediately on its left. | Expression | `p` is null | `p.Address` is null | both non-null | |---|---|---|---| | `p?.Address.City` | null | `NullReferenceException` | the city | | `p?.Address?.City` | null | null | the city | | `(p?.Address).City` | `NullReferenceException` | `NullReferenceException` | the city | | `p?.Address?.City ?? "unknown"` | `"unknown"` | `"unknown"` | the city | The third row is the classic trap: parentheses end the chain, so the parenthesized part evaluates to null and `.City` then runs on that null. ## Step by step: `p?.Address?.City ?? "unknown"` 1. `p` is evaluated once and tested. If it is null, the whole chain `p?.Address?.City` is null and C# jumps straight to `??`. 2. Otherwise `p.Address` is read and tested by the second `?.`. If it is null, the chain is null and again control goes to `??`. 3. Otherwise `City` is read; that string is the chain's value. 4. `??` looks at the chain's value. Only if it is null does it evaluate `"unknown"`. The expression never throws for a null `p` or a null `Address`, and each value in it is read at most once. ## Where to put each `?.` 1. Put `?.` after every value that can legitimately be null in your model: an optional `Address`, a `Profile` that is null for a signed-out visitor. 2. Use a plain `.` after values that are never null once their owner exists, such as a `List<string> Tags` the constructor always creates. Writing `?.` everywhere hides the bug when a "never null" member turns out null. 3. Finish with `??` when the consumer needs a real value: a display string, a count, a default label. With nullable reference types enabled, the compiler helps here: if `Address` is declared `Address?`, then `p?.Address.City` produces warning CS8602 (dereference of a possibly null reference) at `.City`. It is a **warning**, not an error, so the code still compiles and still throws at run time; the warnings themselves are covered in the lesson on nullable reference types. ## `?[]` and arrays or indexers `?[]` follows the same rules for arrays, lists, dictionaries and any indexer: `recentAvatars?[0]` is null when `recentAvatars` is null, and `recentAvatars?[0]?.Url` guards both the collection and the element. It does not protect against a missing key or an index out of range; those throw exactly as `[]` does. ## Common misreadings - "`?.` makes the whole line null-safe" — it makes the **chain** skip when its operand is null, nothing more. - "`?.` returns a default value" — it returns null; `??` is what supplies a default. - "One `?.` at the start is enough" — only if every later link can never be null. - "Parentheses only group" — around a conditional access they cut the short-circuit. In code review, read each `?.` as a question: "can this specific value be null here?" If the answer is no, the `?.` is noise; if the answer is yes for a value further right that has only a `.`, there is a latent `NullReferenceException`.

  • Does `p?.Address.Format(Log())` call `Log()` when `p` is null?
    No. The argument list is part of the short-circuited chain, so when `p` is null C# skips `Address`, the `Format` call and the evaluation of its arguments. `Log()` runs only when `p` is non-null. That is why side effects inside a `?.` chain are easy to miss in review.
  • Is `p?.Name` safe if another thread sets `p` to null between the test and the access?
    Yes for the read of `p` itself: `?.` evaluates its operand once into a temporary, tests that temporary and accesses the member through it. Another thread can change the field or variable afterwards, but this expression keeps using the value it already read. It does not make the member access itself thread-safe.

A visit along a corridor where each ?. is a knock before a door: if nobody answers, you stop and report "nobody home" without walking further; a plain . walks straight in without knocking, and the visit fails if that room is empty.

  • One ?. at the start makes every later member access null-safe
  • ?. returns the type's default value, such as 0 or an empty string
  • Parentheses around a ?. chain never change what is evaluated
  • The arguments of a skipped method call are still evaluated
  • p?.Address.City cannot throw because the line already uses ?.
open as a page

In C#, when do `??` and `??=` evaluate their right-hand operand, and what does `_avatars ??= new AvatarCache()` return?

level: middleimportance: must knowfreq 62%

basics

~20 s

Both evaluate the right operand only when the left one is null. _avatars ??= new AvatarCache() constructs and stores a cache on the first call and returns the stored instance on every later call, without constructing again.

open as a page

In C#, why does `int count = profile?.Tags.Count;` fail to compile, and what type does `?.` give a value-type member?

level: middleimportance: should knowfreq 52%

basics

~20 s

The ?. operator must be able to return null, so a non-nullable value-type member such as Count (an int) comes back as int?. Assigning an int? to an int is error CS0266; add ?? 0 to get an int.

open as a page

A C# cleanup rewrites `if (avatar != null) avatar.Render();` as `avatar?.Render();`; why does that change behaviour when Avatar's `==` treats a disposed instance as null?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The old guard calls Avatar's overloaded != operator, which reports a disposed avatar as null, so Render is skipped. ?. only checks whether the reference is null, so the rewrite calls Render on the disposed avatar. ?? and ??= behave the same way.

open as a page

In C# 14, what happens to `profile?.DisplayName = BuildDisplayName();` when `profile` is null, and which forms does the compiler still reject?

level: seniorimportance: nice to knowfreq 24%

basics

~10 s

Nothing happens: since C# 14, ?. on the left of an assignment skips the whole assignment, and BuildDisplayName() is not even called. Compound operators work; ++, -- and ref uses are still rejected.

open as a page