Nullable and Pattern Matching
Nullable Value Types
A nullable value type can hold a normal value or null.
nullable value
A nullable value type uses `?`, such as `int?`, to allow `null`.
Nullable Value Types
NullableValueTypes.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int? score = 90;
bool hasScore = score.HasValue;
int shown = score.GetValueOrDefault();
Console.WriteLine($"hasScore={hasScore}");
Console.WriteLine($"shown={shown}");
}
}
using System;
class Program
{
static void Main()
{
int? score = null;
bool hasScore = score.HasValue;
int shown = score.GetValueOrDefault();
Console.WriteLine($"hasScore={hasScore}");
Console.WriteLine($"shown={shown}");
}
}
using System;
class Program
{
static void Main()
{
int? score = 75;
bool hasScore = score.HasValue;
int shown = score.GetValueOrDefault();
Console.WriteLine($"hasScore={hasScore}");
Console.WriteLine($"shown={shown}");
}
}
score ← 90, hasScore ← True, shown ← 90
4{5 static void Main()6 {7 int? score→ 90 = 90; //@score=null, 758 bool hasScore→ True = score.HasValueTrue;9 int shown→ 90 = score90.GetValueOrDefault();1011 Console.WriteLine($"hasScore={hasScoreTrue}");12 Console.WriteLine($"shown={shown90}");13 }outputhasScore=True shown=90
score ← (empty), hasScore ← False, shown ← 0
4{5 static void Main()6 {7 int? score→ (empty) = null;8 bool hasScore→ False = score.HasValueFalse;9 int shown→ 0 = score(empty).GetValueOrDefault();1011 Console.WriteLine($"hasScore={hasScoreFalse}");12 Console.WriteLine($"shown={shown0}");13 }outputhasScore=False shown=0
score ← 75, hasScore ← True, shown ← 75
4{5 static void Main()6 {7 int? score→ 75 = 75;8 bool hasScore→ True = score.HasValueTrue;9 int shown→ 75 = score75.GetValueOrDefault();1011 Console.WriteLine($"hasScore={hasScoreTrue}");12 Console.WriteLine($"shown={shown75}");13 }outputhasScore=True shown=75