Null-Coalescing Operators
?? and ??= defaults.
Supplying a Fallback
Often you want to use a value if it exists, or a default if it is null. The null-coalescing operator ?? does exactly this.
a ?? b means: use a if it is not null, otherwise use b.
string input = null;
string name = input ?? "Guest";
System.Console.WriteLine(name);How ?? Evaluates
The left side is evaluated first. If it is non-null, the right side is never evaluated at all.
This short-circuiting means an expensive fallback only runs when actually needed.
string cached = "data";
string value = cached ?? Compute();
System.Console.WriteLine(value);
// Compute() is never called hereAll lessons in this course
- Nullable Value Types
- Null-Conditional Operator
- Null-Coalescing Operators
- Guarding Against Nulls