Safe Navigation
Safe Member Access (?.)
The ?. operator short-circuits to null/zero if the receiver is null:
Person? p = null;string name = p?.Name ?? "Unknown"; // "Unknown"
int len = str?.Length ?? 0;Chained Navigation
Multiple ?. operators can be chained for nested access:
Outer? o = GetOuter();int val = o?.inner?.value ?? -1;Safe Indexing (?[)
int[]? arr = null;int val = arr?[0] ?? -1; // -1Null Coalescing (??)
Returns the left operand if non-null, otherwise the right:
Person? p = null;Person fallback = p ?? defaultPerson;Null Coalescing Assignment (??=)
Assigns the right-hand side only if the left is null:
Person? p = null;p ??= new Person("Default");// p is now Person("Default")
p ??= new Person("Other");// p is still Person("Default")Type Rules
| Receiver | ?. behavior |
|---|---|
Type? (nullable) | Null check, returns null/zero if null |
Type! (non-null) | Warning (redundant), still works |
Type (value) | Compile error — not nullable |
T* (pointer) | Requires unsafe, performs null check |
Example
type Node{ int value; Node? next;}
int GetThirdValue(Node? head){ return head?.next?.next?.value ?? -1;}
Node? list = null;Console.WriteLine($"{GetThirdValue(list)}"); // -1