SyntaxStudy
Sign Up
C# Nullable Types and Null Safety
C# Beginner 1 min read

Nullable Types and Null Safety

Null reference exceptions are historically one of the most common runtime errors in object-oriented languages. C# tackles this with two complementary mechanisms: nullable value types (`int?`, `bool?`) and nullable reference types (the compiler-enforced annotation system introduced in C# 8). With nullable reference types enabled, the compiler performs flow analysis to determine when a variable might be null. Accessing a member on a potentially-null value without a null check produces a warning. The null-conditional operator `?.` and null-coalescing operator `??` provide concise ways to handle null values inline. The null-forgiving operator `!` suppresses a nullable warning when you know a value cannot be null but the compiler cannot prove it. Use it sparingly; overuse defeats the purpose of the nullable analysis and can mask genuine bugs.
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());
}