Null-Conditional & Null-Coalescing Operators
Combine ?., ?[], ?? and ??= to write concise null-safe code without verbose null checks.
Null-Safe Code Patterns
C# provides three dedicated operators to handle null values concisely: the null-conditional (?., ?[]), null-coalescing (??), and null-coalescing assignment (??=). Together they eliminate most verbose null-check boilerplate.
Null-Conditional Operator: ?.
?. short-circuits to null if the left side is null instead of throwing a NullReferenceException. The result type becomes nullable.
User? user = GetUser(id);
// Without ?.:
string? name = null;
if (user != null) name = user.Name;
// With ?.:
string? name2 = user?.Name;
// Chained:
string? city = user?.Address?.City;
// Method call:
string? upper = user?.Name?.ToUpper();All lessons in this course
- Enabling & Understanding NRT
- Annotations: ?, !, MaybeNull & NotNull
- Null-Conditional & Null-Coalescing Operators
- Migrating a Codebase to NRT