C#
Beginner
1 min read
Nullable Types and Null Safety
Example
#nullable enable // Can also be set project-wide in .csproj
// Nullable value type
int? score = null;
Console.WriteLine(score.HasValue); // False
Console.WriteLine(score.GetValueOrDefault(-1)); // -1
// Null-coalescing assignment
score ??= 0;
Console.WriteLine(score); // 0
// Nullable reference type
string? middle = null;
// Null-conditional operator: short-circuits to null if left side is null
int? len = middle?.Length; // null, no NullReferenceException
Console.WriteLine(len ?? -1); // -1
// Pattern matching null check
if (middle is null)
Console.WriteLine("No middle name provided");
// Null-coalescing operator in expressions
string display = middle ?? "N/A";
Console.WriteLine(display); // "N/A"
// Chained null-conditionals
string[]? tags = null;
string? firstTag = tags?[0]; // null, no IndexOutOfRangeException
// Non-null assertion — use with caution!
string definitelySet = middle!; // suppresses warning; crashes if null at runtime
// Helper: ArgumentNullException.ThrowIfNull (introduced in .NET 6)
static void PrintName(string? name)
{
ArgumentNullException.ThrowIfNull(name);
Console.WriteLine(name.ToUpper());
}