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)
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.