C# Null Safety
Null safety code checks for null at the exact point where a missing value would do harm. A guard either stops early with a clear exception or takes a safe path around the null.
ThrowIfNull caught
The guard throws for the null name. The catch prints the exception message, which names the parameter.
using System;
#nullable enable
class Program
{
static void Main(string[] args)
{
string? name = null;
try
{
ArgumentNullException.ThrowIfNull(name);
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex.Message);
}
}
}An unguarded read crashes
The text is null and nothing guards the Length read. The program stops with a NullReferenceException.
using System;
class Program
{
static void Main(string[] args)
{
string text = null;
Console.WriteLine(text.Length);
}
}The guarded form
The same read now sits behind a null check. The null case prints a safe fallback line instead of crashing.
using System;
#nullable enable
class Program
{
static void Main(string[] args)
{
string? text = null;
string result = text == null ? "No text" : text.Length.ToString();
Console.WriteLine(result);
}
}Example
using System;
#nullable enable
class Program
{
static void PrintLength(string text)
{
Console.WriteLine(text.Length);
}
static void Main(string[] args)
{
string? word = "hello";
if (word != null)
{
PrintLength(word);
}
string? missing = null;
try
{
ArgumentNullException.ThrowIfNull(missing);
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex.Message);
}
}
}Key points
- ArgumentNullException.ThrowIfNull throws when its argument is null.
- The exception message names the parameter that held null.
- ThrowIfNull does nothing when the argument holds a real value.
- Reading a member through a null reference raises NullReferenceException at runtime.
- That crash gives no parameter name and no planned message.
- A null check or the ?. operator gives code a safe path when null is an expected case.
In this example, the word holds text, so the guard check passes and PrintLength prints 5. The missing value then reaches ThrowIfNull inside a try block. The catch prints the message naming the missing parameter.
Note
Guard at the boundary where a value enters the code, so failures surface close to their cause.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ArgumentNullException.ThrowIfNull do when its argument is null?