Null-Coalescing Operators
Use ?? and ??= to provide fallbacks.
The ?? Operator
The null-coalescing operator ?? returns its left operand if it is not null, otherwise the right operand. It is a compact fallback.
using System;
class Program {
static void Main() {
int? maybe = null;
int value = maybe ?? -1;
Console.WriteLine(value);
}
}?? Picks the First Non-Null
If the left side has a value, that value wins and the right side is ignored.
using System;
class Program {
static void Main() {
int? a = 7;
Console.WriteLine(a ?? 0);
}
}All lessons in this course
- Introducing Nullable Value Types
- HasValue and Value Properties
- Null-Coalescing Operators
- Nullable in Calculations