Null Coalescing (??)
In this page:
Null Coalescing (??)
The ?? operator returns its left operand if it isn't null, otherwise it returns the right operand — a compact way to supply defaults. ??= goes further, assigning the right side only if the variable is currently null. Both operators exist specifically to reduce verbose null-checking if statements.
Note: x ??= defaultValue; is shorthand for if (x == null) x = defaultValue;.
Example: Null Coalescing (??)
using System;
class Program
{
static void Main(string[] args)
{
string name = null;
string displayName = name ?? "Guest";
Console.WriteLine(displayName);
string city = null;
city ??= "Unknown";
Console.WriteLine(city);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: