IC Improve Code Recipes

Recipe 8.1 · C#

Guard Clauses with the Built-in Throw Helpers

Problem

Public methods receive arguments they cannot work with: a null dependency, an empty customer ID, a negative amount. Without a check, the method fails later with a NullReferenceException or, worse, writes bad data. With hand-written checks, every method starts with six lines of if and throw, and the parameter names in the messages drift out of date when someone renames a parameter.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
public Invoice CreateInvoice(string customerId, decimal amount,
    int termsDays)
{
    if (customerId == null)
        throw new ArgumentNullException("custId");
    if (customerId == "")
        throw new Exception("Customer is required");
    if (amount <= 0)
        throw new ArgumentException("bad amount");
    // termsDays never checked
    ...
}

Three problems show up here. The parameter name in the first exception is wrong because the parameter was renamed years ago. The second check throws a bare Exception, so callers cannot tell an argument problem from a database outage. And whitespace-only IDs pass straight through.

The improved recipe

Since .NET 6, and much more so in .NET 8, the exception types themselves carry static throw helpers. They use CallerArgumentExpression to fill in the parameter name for you, so a rename can never make the message lie. For the few checks the framework does not cover, a small Guard class follows the same pattern.

C#
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace ImproveCode.Validation;

public static class Guard
{
    public static IReadOnlyCollection<T> NotEmpty<T>(
        IReadOnlyCollection<T>? value,
        [CallerArgumentExpression(nameof(value))]
        string? paramName = null)
    {
        ArgumentNullException.ThrowIfNull(value, paramName);
        if (value.Count == 0)
        {
            throw new ArgumentException(
                "The collection must contain at least one item.",
                paramName);
        }
        return value;
    }

    public static TEnum Defined<TEnum>(
        TEnum value,
        [CallerArgumentExpression(nameof(value))]
        string? paramName = null)
        where TEnum : struct, Enum
    {
        if (!Enum.IsDefined(value))
        {
            throw new ArgumentOutOfRangeException(
                paramName, value,
                $"{value} is not a defined {typeof(TEnum).Name}.");
        }
        return value;
    }
}

public enum PaymentTerms { Net15 = 15, Net30 = 30, Net60 = 60 }

public sealed record InvoiceDraft(
    string CustomerId,
    decimal Amount,
    PaymentTerms Terms,
    IReadOnlyCollection<string> Lines);

public sealed class InvoiceFactory
{
    private readonly TimeProvider _clock;

    public InvoiceFactory(TimeProvider clock)
    {
        ArgumentNullException.ThrowIfNull(clock);
        _clock = clock;
    }

    public InvoiceDraft Create(
        string customerId,
        decimal amount,
        PaymentTerms terms,
        IReadOnlyCollection<string> lines)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(customerId);
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        ArgumentOutOfRangeException.ThrowIfGreaterThan(
            amount, 1_000_000m);
        Guard.Defined(terms);
        Guard.NotEmpty(lines);

        return new InvoiceDraft(
            customerId.Trim(), amount, terms, lines);
    }

    public DateOnly DueDate(PaymentTerms terms)
    {
        Guard.Defined(terms);
        DateOnly today =
            DateOnly.FromDateTime(_clock.GetUtcNow().UtcDateTime);
        return today.AddDays((int)terms);
    }
}

How it works

ArgumentNullException.ThrowIfNull and ArgumentException.ThrowIfNullOrWhiteSpace take the argument and nothing else. The compiler passes the text of the argument expression, so the exception says customerId, not a string someone typed. ArgumentOutOfRangeException gained a family of generic helpers in .NET 8: ThrowIfNegative, ThrowIfZero, ThrowIfNegativeOrZero, ThrowIfGreaterThan, ThrowIfLessThan, ThrowIfEqual and their siblings. They work for any numeric type, including decimal, and the message includes the actual value, which saves a trip to the debugger.

The Guard class covers two gaps I hit often: an empty collection, and an enum value that is not one of the named members. Casting any integer to an enum compiles, so (PaymentTerms)7 is a perfectly legal value until it reaches a switch. Enum.IsDefined<TEnum> is the generic overload, with no boxing. Both guard methods return the value, so you can use them inline in a constructor assignment if you like.

The throw helpers are also cheap. The throwing path lives in a separate method that the JIT does not inline, so the happy path is a compare and a branch.

Variations and pitfalls

  • Guards are for programmer errors. A guard clause says "the caller broke the contract." It is not how you tell a user that the e-mail field is blank. User input goes through the validators in the next recipes and comes back as a list of messages, not an exception.
  • Don't guard private methods to death. Check at public and protected entry points. Inside a class, trust your own code and let nullable reference types do the work.
  • Flags enums need a different check. Enum.IsDefined returns false for combined flag values such as Read | Write. For [Flags] enums, compare against a mask of all valid bits instead.
  • Keep the old package away. Several third-party "Guard" packages predate these helpers. In new code the built-in ones are enough, and they need no dependency.

On .NET Framework

CallerArgumentExpression is a compiler feature, so it works on .NET Framework 4.8 with C# 10 or later if you declare the attribute class yourself (in the System.Runtime.CompilerServices namespace). The static throw helpers do not exist there. Put equivalents in your own Guard class with the same names, and the call sites will move to .NET 8 unchanged.