Nullable and Pattern Matching
Null Coalescing
The null-coalescing operator chooses a fallback for a null value.
null coalescing
The `??` operator returns the left value unless it is null.
Null Coalescing
NullCoalescing.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int? count = null;
int fallback = 1;
int display = count ?? fallback;
Console.WriteLine($"hasCount={count.HasValue}");
Console.WriteLine($"display={display}");
}
}
using System;
class Program
{
static void Main()
{
int? count = 3;
int fallback = 1;
int display = count ?? fallback;
Console.WriteLine($"hasCount={count.HasValue}");
Console.WriteLine($"display={display}");
}
}
count ← (empty), fallback ← 1, display ← 1
4{5 static void Main()6 {7 int? count→ (empty) = null; //@count=3, null8 int fallback→ 1 = 1;9 int display→ 1 = count(empty) ?? fallback1;1011 Console.WriteLine($"hasCount={count.HasValueFalse}");12 Console.WriteLine($"display={display1}");13 }outputhasCount=False display=1
count ← 3, fallback ← 1, display ← 3
4{5 static void Main()6 {7 int? count→ 3 = 3;8 int fallback→ 1 = 1;9 int display→ 3 = count3 ?? fallback1;1011 Console.WriteLine($"hasCount={count.HasValueTrue}");12 Console.WriteLine($"display={display3}");13 }outputhasCount=True display=3