Skip to content

C# Feature – Null-coalescing ??

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.

C# 2 (2005)

string? name = GetName();
string display = (name != null) ? name : "(unknown)";
string? name = GetName();
string display = name ?? "(unknown)";
Console.WriteLine((string?)null ?? "fallback"); // prints "fallback"
  • ?? only checks for null, not emptiness; combine with checks for empty strings when needed.
  • Prefer ??= to assign defaults lazily.
  • ??= (null-coalescing assignment) added in C# 8.