Phase 6 of 30 · Topic 6.3

Modern Guard Clauses: `ArgumentNullException.ThrowIfNull` (.NET 8/9)

1Concept

Modern .NET provides high-performance zero-overhead throw helpers like `ArgumentNullException.ThrowIfNull(arg)`. The JIT compiles the throw logic out-of-line (cold path) to keep the method's hot path dense and cache-efficient.

2Architecture Diagram

Incoming Parameter
       │
   Is null?
     ├── YES ──> Jumps to Cold Throw Helper (Out-of-line)
     └── NO  ──> Direct execution (Inlined Hot Path CPU Cache Hit)

3Code Example

C# 13 & .NET 9
using System;

public class GuardClauseDemo
{
    public static void RegisterUser(string username, string email)
    {
        // .NET 8/9 Optimized Zero-Cost Guard Helpers
        ArgumentNullException.ThrowIfNull(username);
        ArgumentException.ThrowIfNullOrWhiteSpace(email);

        Console.WriteLine($"User Registered: {username} ({email})");
    }

    public static void Main()
    {
        RegisterUser("alex_architect", "alex@enterprise.cloud");
        try
        {
            RegisterUser(null!, "invalid");
        }
        catch (ArgumentNullException ex)
        {
            Console.WriteLine($"Caught Expected Guard Exception: {ex.ParamName}");
        }
    }
}

4Expected Output

User Registered: alex_architect (alex@enterprise.cloud)
Caught Expected Guard Exception: username

5Key Takeaways

  • Use `ArgumentNullException.ThrowIfNull()` instead of legacy `if (x == null) throw new ...` blocks.
  • CallerArgumentExpression auto-captures parameter names at compile time.
  • Keeps method byte size small for aggressive RyuJIT inlining.