Null Coalescing (??)
The double question mark gives you a backup value when something is empty, like 'use my lunchbox, or if I forgot it, buy lunch'. It supplies a default whenever the first thing is null.
In this page:
Syntax
type result = value ?? fallback; // fallback used when value is null
variable ??= fallback; // assign only if variable is null
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
??on a value type that cannot be null, which is a compile error. - Confusing
??(default when null) with?:(conditional on a bool). - Expecting
??to treat an empty string as null, when it only checks for null.
Chapter Summary
- Arithmetic, comparison, and logical operators build expressions.
- Bitwise operators work on the bits of values.
- The ternary operator and null coalescing (
??) provide short ways to choose values.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: