C# Feature – Null-coalescing ??
Overview
Section titled “Overview”The null-coalescing operator ??
returns its left operand if it is not null; otherwise, it evaluates and returns the right operand. Use it for simple defaults.
Introduced In
Section titled “Introduced In”C# 2 (2005)
Before
Section titled “Before”string? name = GetName();string display = (name != null) ? name : "(unknown)";
string? name = GetName();string display = name ?? "(unknown)";
Annotated Example
Section titled “Annotated Example”Console.WriteLine((string?)null ?? "fallback"); // prints "fallback"
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”??
only checks for null, not emptiness; combine with checks for empty strings when needed.- Prefer
??=
to assign defaults lazily.
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”??=
(null-coalescing assignment) added in C# 8.