ZetCode

C# guard clauses

last modified November 15, 2026

This article shows how to validate method arguments with guard clauses in C#. We use the static ThrowIf helpers on the argument exception classes, guard a constructor, and write a custom guard that captures the failing expression with CallerArgumentExpression.

A guard clause is a check at the start of a method that rejects invalid input before any work is done. It keeps the main logic free of nesting and makes the contract of the method explicit: if the guard passes, the rest of the method can assume the value is usable. A guard throws an exception rather than returning an error code, so a caller that ignores the contract fails immediately and at the point of the mistake.

The .NET class library supplies static helpers that both check the value and build a consistent exception. Their messages include the parameter name, and with nullable reference types enabled the compiler can also see that the value is not null after the call. The helpers are preferable to hand-written if (x == null) throw new ArgumentNullException(nameof(x)); because they are shorter, allocation-free on the success path, and updated with the framework.

Null guards

ArgumentNullException.ThrowIfNull checks a reference, a nullable value type, or a pointer. When the value is null, it throws an ArgumentNullException whose parameter name comes from the argument expression. After the call, the compiler's flow analysis knows that the parameter is not null.

Program.cs
try
{
    Report(null!);
}
catch (ArgumentNullException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

static void Report(string text)
{
    ArgumentNullException.ThrowIfNull(text);
    Console.WriteLine(text.ToUpperInvariant());
}

The caller passes null despite the non-nullable parameter, which is what happens when a value comes from older code or from reflection. The guard rejects it before ToUpperInvariant can throw a NullReferenceException.

ArgumentNullException.ThrowIfNull(text);

The helper derives the parameter name text from the argument expression, so no nameof is needed. Passing an explicit name is still possible with the two-argument overload, which is useful when the value comes from a different expression, such as ThrowIfNull(options, nameof(options)).

$ dotnet run
ArgumentNullException: Value cannot be null. (Parameter 'text')

String and numeric guards

Empty and whitespace-only strings are a separate failure mode from null, and negative numbers are another. The ArgumentException and ArgumentOutOfRangeException classes provide helpers for both. They report the parameter name in the same format as the null guard.

Program.cs
try
{
    AddUser("  ");
}
catch (ArgumentException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

try
{
    SetAge(-1);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

static void AddUser(string name)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(name);
    Console.WriteLine($"added {name}");
}

static void SetAge(int age)
{
    ArgumentOutOfRangeException.ThrowIfNegative(age, nameof(age));
    Console.WriteLine($"age {age}");
}

AddUser rejects a name that is null, empty, or only whitespace. SetAge rejects a negative age and includes the parameter name explicitly.

ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentOutOfRangeException.ThrowIfNegative(age, nameof(age));

ThrowIfNullOrWhiteSpace lives on ArgumentException because an empty string is a bad value, not a missing object. The negative check lives on ArgumentOutOfRangeException because the value is outside the allowed range. Both helpers have overloads that accept a paramName; without one, the compiler generates it from the expression.

$ dotnet run
ArgumentException: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'name')
ArgumentOutOfRangeException: age ('-1') must be a non-negative value. (Parameter 'age')
Actual value was -1.

Range guards

For numeric ranges, the helpers cover the common comparisons without writing the condition by hand. Each one accepts an optional parameter name and produces a message that states the boundary and the actual value.

Program.cs
try
{
    Console.WriteLine(ApplyDiscount(120));
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

try
{
    Console.WriteLine(ApplyDiscount(0));
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

static decimal ApplyDiscount(decimal percent)
{
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(percent);
    ArgumentOutOfRangeException.ThrowIfGreaterThan(percent, 100);

    return 100 - percent;
}

The method accepts a percentage greater than zero and at most 100. The first call is above the upper bound, and the second is zero.

ArgumentOutOfRangeException.ThrowIfNegativeOrZero(percent);
ArgumentOutOfRangeException.ThrowIfGreaterThan(percent, 100);

The two guards form a closed interval: the first rejects zero and negative values, the second rejects values above 100. The order matters only for the message the caller sees. The family also includes ThrowIfNegative, ThrowIfLessThan, ThrowIfLessThanOrEqual, ThrowIfGreaterThanOrEqual, and ThrowIfZero, so most comparisons have a built-in form.

$ dotnet run
ArgumentOutOfRangeException: percent ('120') must be less than or equal to '100'. (Parameter 'percent')
Actual value was 120.
ArgumentOutOfRangeException: percent ('0') must be a non-negative and non-zero value. (Parameter 'percent')
Actual value was 0.

Guarding a constructor

A constructor is the most important place for guards: once an object exists, every method can rely on its fields being valid. A null dependency that is stored in a field would otherwise fail much later, far from the call that caused it.

Program.cs
try
{
    _ = new OrderService(null!);
}
catch (ArgumentNullException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

public sealed class OrderService
{
    private readonly IRepository _repository;

    public OrderService(IRepository repository)
    {
        ArgumentNullException.ThrowIfNull(repository);
        _repository = repository;
    }

    public IRepository Repository => _repository;
}

public interface IRepository;

The constructor validates the repository before assigning it. The exception names the repository parameter, so the caller knows which argument was wrong.

ArgumentNullException.ThrowIfNull(repository);
_repository = repository;

Placing the guard before the assignment means the object is never left in a half-initialized state. If the class has several dependencies, guard them in the order they appear in the parameter list so the first reported error is also the first argument a caller reads.

$ dotnet run
ArgumentNullException: Value cannot be null. (Parameter 'repository')

Custom guards with CallerArgumentExpression

Not every rule has a built-in helper. A custom guard can still produce a useful message by capturing the source text of the condition. The CallerArgumentExpression attribute tells the compiler to pass the expression that was used for an argument, so the guard does not need a hand-written description for every check.

Program.cs
using System.Runtime.CompilerServices;

try
{
    Register("Bob", -5);
}
catch (ArgumentException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

static void Register(string name, int age)
{
    Require(age >= 0);
    Require(name.Length <= 20);

    Console.WriteLine($"{name}: {age}");
}

static void Require(bool condition,
    [CallerArgumentExpression(nameof(condition))] string? expression = null)
{
    if (!condition)
    {
        throw new ArgumentException($"Guard failed: {expression}");
    }
}

Require takes the condition and lets the compiler fill in the text age >= 0. When the condition is false, the exception message contains the exact check that failed.

static void Require(bool condition,
    [CallerArgumentExpression(nameof(condition))] string? expression = null)

The attribute is applied to the parameter that receives the text, and its argument names the parameter whose expression should be captured. The captured parameter must be optional so that callers can omit it. This is the same mechanism that ArgumentNullException.ThrowIfNull uses to report the argument name without nameof.

$ dotnet run
ArgumentException: Guard failed: age >= 0

Which exception to throw

The exception type tells the caller what kind of mistake was made. ArgumentNullException means a required object was missing. ArgumentException means a value was present but invalid, such as an empty string or a malformed identifier. ArgumentOutOfRangeException means a value fell outside an accepted interval. All three derive from ArgumentException, so a caller can catch the base type when it does not care about the difference.

Guard clauses belong at the public boundary of a method or constructor, not after every local step. Internal code that already validated its input should not re-check the same condition; repeating guards makes the method noisy and suggests that the invariants are not trusted. For conditions that indicate a bug in the program rather than bad input from a caller, Debug.Assert is the better tool because it disappears from release builds.

With nullable reference types enabled, a guard also improves the flow analysis. After ThrowIfNull(text), the compiler treats text as non-null for the rest of the method, so no null-forgiving operator is needed. The nullable types and exception tutorials cover the annotation and exception sides in more detail.

Source

ArgumentNullException.ThrowIfNull

ArgumentException.ThrowIfNullOrWhiteSpace

ArgumentOutOfRangeException

Caller information attributes

In this article we have written guard clauses with the argument exception helpers. See also the exception, constructor, nullable types, and attributes tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.