Exceptions and Defensive Coding
Null Checks
A null check chooses a fallback before using a missing nullable value.
Null Checks
NullChecks.cs
using System;
class Program
{
static string DisplayScore(int? score)
{
if (!score.HasValue)
{
return "missing";
}
return "score:" + score.Value;
}
static void Main()
{
int? score = ;
string display = DisplayScore(score);
Console.WriteLine($"hasScore={score.HasValue}");
Console.WriteLine($"display={display}");
}
}
using System;
class Program
{
static string DisplayScore(int? score)
{
if (!score.HasValue)
{
return "missing";
}
return "score:" + score.Value;
}
static void Main()
{
int? score = ;
string display = DisplayScore(score);
Console.WriteLine($"hasScore={score.HasValue}");
Console.WriteLine($"display={display}");
}
}
using System;
class Program
{
static string DisplayScore(int? score)
{
if (!score.HasValue)
{
return "missing";
}
return "score:" + score.Value;
}
static void Main()
{
int? score = ;
string display = DisplayScore(score);
Console.WriteLine($"hasScore={score.HasValue}");
Console.WriteLine($"display={display}");
}
}
null check
A null check protects code before reading from a value that might be missing.