skip to content

Null Safety Rules

Nullable reference types, nullable value types, null operators and attributes: how C# catches null at compile time. Interviewers ask what the warnings really guarantee.

on this pageshow

explore

questions

21

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

With nullable reference types enabled in C#, what does writing string? instead of string change at compile time and at run time?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Only the compiler's analysis changes. string? says the value may be null, so unchecked dereferences warn; string promises non-null, so a possible null flowing in warns. Both are System.String at run time, with no inserted null checks.

open as a page

In C#, what is `int?`, and what do `HasValue`, `Value` and `GetValueOrDefault()` do when it holds no value?

level: juniorimportance: must knowfreq 72%

basics

~10 s

int? is shorthand for the struct Nullable<int>. When it is empty, HasValue is false, Value throws InvalidOperationException, and GetValueOrDefault() returns 0, or the fallback you pass to GetValueOrDefault(T).

open as a page

With nullable reference types enabled, how do you annotate a C# cache's TryGetValue out parameter so callers get no warning after a true result?

level: middleimportance: must knowfreq 60%

basics

~10 s

Declare it [NotNullWhen(true)] out string? value: after a true return the value is not-null, after false maybe-null. For a generic TValue use [MaybeNullWhen(false)] out TValue value, as Dictionary<TKey,TValue>.TryGetValue does.

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#, what does the null-forgiving operator ! do at compile time and at run time, and when does using it become a problem?

level: middleimportance: must knowfreq 60%

basics

~20 s

Postfix ! tells the compiler an expression is not null, suppressing nullable warnings for that expression. It emits no code and no check: x! evaluates to x, so a wrong ! simply moves the NullReferenceException to a later line.

open as a page

In C#, what do lifted operators return when an `int?` operand is null, and how do `==` and `!=` treat two nulls?

level: middleimportance: must knowfreq 58%

basics

~20 s

Lifted arithmetic and bitwise operators on int? return null when either operand is null, so age + 5 is null and never throws. Equality returns a plain bool: null == null is true and null != 5 is true.

open as a page

With nullable reference types enabled, why does C# warn after your own IsBlank(string?) check but not after string.IsNullOrWhiteSpace?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Nullable analysis does not look inside the method you call; it reads the signature. string.IsNullOrWhiteSpace declares [NotNullWhen(false)] string? value, so a false result proves not-null. Your helper needs the same attribute on its parameter.

open as a page

In C#, how do [NotNull] and [DoesNotReturn] let a team's own null-guard helper remove nullable warnings at its call sites?

level: middleimportance: should knowfreq 35%

basics

~20 s

Declare the guard's parameter [NotNull] object? value: callers may pass null, but once the call returns the argument is not-null. Mark an always-throwing helper [DoesNotReturn] so nullable analysis treats code after its call as unreachable.

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

In a C# project, what do the Nullable property values enable, warnings, annotations and disable each turn on, and how do #nullable directives override them?

level: middleimportance: should knowfreq 55%

basics

~20 s

The nullable context has two flags: annotations (whether ? and non-nullable types mean anything) and warnings (whether null-state warnings are reported). enable sets both, disable neither, warnings and annotations one each; #nullable directives change either flag for the rest of a file.

open as a page

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%

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.

open as a page

In C#, what does T? mean on a method of an unconstrained generic Store<T>, and which nullable attributes express the same contract?

level: seniorimportance: should knowfreq 30%

basics

~20 s

On an unconstrained T, T? is an annotation meaning 'may be default': for T = string it is string?, for T = int it stays int, not int?. So Store<int>.GetOrDefault returns 0 for a missing key.

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

A C# service built with <Nullable>enable</Nullable> and no nullable warnings throws NullReferenceException on a non-nullable string property; how can null get there?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Non-nullable is a compile-time promise with no run-time check. Null still arrives from code the analysis never sees: deserializers and reflection, new arrays and default structs, callers or libraries compiled with nullable disabled, and ! or null! suppressions.

open as a page

In C#, what does boxing an `int?` produce when it is empty and when it holds 42, and why does `GetType()` never report `Nullable<int>`?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Boxing an empty int? produces a null reference; boxing one that holds 42 boxes the plain int. No boxed Nullable<int> ever exists, so GetType() reports System.Int32, or throws NullReferenceException on an empty instance.

open as a page

In a C# generic method returning `T?`, why is `T?` a `Nullable<T>` under `where T : struct` but plain `int` when an unconstrained `T` is `int`?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Under where T : struct, T? is Nullable<T>, so the method can return null and callers get an empty value. On an unconstrained T, T? is only an annotation: for T = int it is plain int, and return default yields 0.

open as a page

A C# survey report counts responses with `Age >= 18` and with `Age < 18` on an `int? Age`; why don't the two counts add up to the total?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Lifted ordering comparisons on int? return false whenever an operand is null, so a response with no age is neither >= 18 nor < 18 and drops out of both counts; !(Age < 18) adds them back.

open as a page

A ten-year-old C# customer-support backend turns on <Nullable>enable</Nullable> and gets two thousand warnings; how would you plan the migration and decide when nullable warnings become errors?

level: principalimportance: should knowfreq 40%

basics

~20 s

Turn the warnings into a sequenced backlog: pick a project default and #nullable directives, migrate bottom-up from leaf types, fix the APIs that really return null, and make nullable warnings errors once migrated code is clean, so the backlog can only shrink.

open as a page

In C#, why does a constructor that calls an Initialize helper to set non-nullable fields still get CS8618, and how does [MemberNotNull] fix it?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

The compiler checks each constructor without following calls, so fields set only in Initialize look unassigned and CS8618 fires. [MemberNotNull(nameof(_prices), nameof(_region))] on Initialize promises they are not-null on return, and the compiler checks the helper.

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