Argument validation: throw helpers and CallerArgumentExpression

suggest change

Public methods should reject bad arguments right away, with an exception that names the offending parameter. For years that meant an if plus throw new ArgumentNullException(nameof(x)) for every parameter. Modern .NET has one-line static throw helpers for the common checks, and the C# 10 attribute [CallerArgumentExpression] lets them (and your own guards) find out the parameter name without being told:

public void Transfer(Account from, Account to, decimal amount)
{
    ArgumentNullException.ThrowIfNull(from);
    ArgumentNullException.ThrowIfNull(to);
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
    // ...
}

Versions:

.NET 9 and .NET 10 didn't add any helpers, so this is still the full list. The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.

The classic nameof guard is shown in Argument Checking and Guard Clauses, and ?? throw in throw expressions.

ThrowIfNull instead of if + throw

Here is the old way next to the new one:

static void SendOld(string to, string body)
{
    if (to is null)
        throw new ArgumentNullException(nameof(to));
    if (body is null)
        throw new ArgumentNullException(nameof(body));
    // ...
}

static void SendNew(string to, string body)
{
    ArgumentNullException.ThrowIfNull(to);
    ArgumentNullException.ThrowIfNull(body);
    // ...
}

try { SendOld("bob@example.com", null!); }
catch (ArgumentNullException e) { Console.WriteLine($"old: {e.ParamName} | {e.Message}"); }

try { SendNew("bob@example.com", null!); }
catch (ArgumentNullException e) { Console.WriteLine($"new: {e.ParamName} | {e.Message}"); }
old: body | Value cannot be null. (Parameter 'body')
new: body | Value cannot be null. (Parameter 'body')

The exception is exactly the same, but we never wrote "body" or nameof(body). Here is the signature of ThrowIfNull:

public static void ThrowIfNull(
    [NotNull] object? argument,
    [CallerArgumentExpression(nameof(argument))] string? paramName = null);

When you leave out paramName, the compiler fills it in with the source text of the expression you passed as argument. For ThrowIfNull(body) that text is "body". This is the same idea as [CallerMemberName] and [CallerLineNumber]: the value is decided at compile time and baked into the call site, so nothing is looked up at run time.

Why this beats the nameof guard:

It works with any expression

Because the parameter name is just the argument's source text, you can check a property path and the message says exactly what was null:

Order[] orders =
[
    new(1, new Customer("Ann", "ann@example.com")),
    new(2, null),
    new(3, new Customer("Bob", null)),
];

foreach (var o in orders)
{
    try { Ship(o); }
    catch (ArgumentNullException e) { Console.WriteLine(e.Message); }
}

static void Ship(Order order)
{
    ArgumentNullException.ThrowIfNull(order);
    ArgumentNullException.ThrowIfNull(order.Customer);
    ArgumentNullException.ThrowIfNull(order.Customer.Email);
    Console.WriteLine($"shipping order {order.Id} to {order.Customer.Email}");
}

record Customer(string Name, string? Email);
record Order(int Id, Customer? Customer);
shipping order 1 to ann@example.com
Value cannot be null. (Parameter 'order.Customer')
Value cannot be null. (Parameter 'order.Customer.Email')

The compiler knows the value isn't null afterwards

The argument parameter has the [NotNull] attribute, which tells the nullable reference types flow analysis that if ThrowIfNull returns, the argument wasn't null. That is why order.Customer.Email above gets no "possibly null" warning, even though Customer and Email are declared nullable. You get the run-time check and the compile-time knowledge from the same line.

Strings: ThrowIfNullOrEmpty and ThrowIfNullOrWhiteSpace

For strings, "not null" is rarely enough. ArgumentException.ThrowIfNullOrWhiteSpace rejects null, "" and all-whitespace strings in one call:

string?[] inputs = ["alice", null, "", "   "];

foreach (var name in inputs)
{
    try
    {
        CreateUser(name!);
    }
    catch (ArgumentException e)
    {
        Console.WriteLine($"{e.GetType().Name}: {e.Message}");
    }
}

static void CreateUser(string userName)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(userName);
    Console.WriteLine($"created '{userName}'");
}
created 'alice'
ArgumentNullException: Value cannot be null. (Parameter 'userName')
ArgumentException: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'userName')
ArgumentException: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'userName')

Note that a null string still gets an ArgumentNullException (which derives from ArgumentException), so callers that catch either type keep working. ThrowIfNullOrEmpty is the weaker version that lets whitespace through:

foreach (var s in new string?[] { null, "", " " })
{
    try { ArgumentException.ThrowIfNullOrEmpty(s); Console.WriteLine($"'{s}' accepted"); }
    catch (ArgumentException e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); }
}
ArgumentNullException: Value cannot be null. (Parameter 's')
ArgumentException: The value cannot be an empty string. (Parameter 's')
' ' accepted

Ranges: the ArgumentOutOfRangeException helpers (.NET 8)

.NET 8 added generic helpers for numeric and range checks. The message includes the parameter name, the actual value and the limit, and the exception's ActualValue property is filled in too, which hand-written throw new ArgumentOutOfRangeException(nameof(x)) code almost never bothered to do:

Try(() => Page(items: 10, pageSize: 0, pageNumber: 1));
Try(() => Page(items: 10, pageSize: 500, pageNumber: 1));
Try(() => Page(items: 10, pageSize: 20, pageNumber: -3));
Try(() => SetVolume(1.5));
Try(() => SetVolume(0.75));

static void Page(int items, int pageSize, int pageNumber)
{
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize);
    ArgumentOutOfRangeException.ThrowIfGreaterThan(pageSize, 100);
    ArgumentOutOfRangeException.ThrowIfLessThan(pageNumber, 1);
    Console.WriteLine($"page {pageNumber}, {pageSize} per page");
}

static void SetVolume(double volume)
{
    ArgumentOutOfRangeException.ThrowIfNegative(volume);
    ArgumentOutOfRangeException.ThrowIfGreaterThan(volume, 1.0);
    Console.WriteLine($"volume set to {volume}");
}

static void Try(Action a)
{
    try { a(); }
    catch (ArgumentOutOfRangeException e)
    {
        Console.WriteLine(e.Message);
        Console.WriteLine($"  ParamName={e.ParamName}, ActualValue={e.ActualValue ?? "(null)"}");
    }
}
pageSize ('0') must be a non-negative and non-zero value. (Parameter 'pageSize')
Actual value was 0.
  ParamName=pageSize, ActualValue=0
pageSize ('500') must be less than or equal to '100'. (Parameter 'pageSize')
Actual value was 500.
  ParamName=pageSize, ActualValue=500
pageNumber ('-3') must be greater than or equal to '1'. (Parameter 'pageNumber')
Actual value was -3.
  ParamName=pageNumber, ActualValue=-3
volume ('1.5') must be less than or equal to '1'. (Parameter 'volume')
Actual value was 1.5.
  ParamName=volume, ActualValue=1.5
volume set to 0.75

Read the names as "throw if": ThrowIfGreaterThan(pageSize, 100) throws when pageSize > 100, so 100 itself is allowed. It's easy to get this backwards, because the condition is the opposite of what an if that accepts the value would say.

The helpers are generic, so they work with any matching type, not just int:

Helper Throws when Constraint on T
ThrowIfZero(value) value == 0 INumberBase<T>
ThrowIfNegative(value) value < 0 INumberBase<T>
ThrowIfNegativeOrZero(value) value <= 0 INumberBase<T>
ThrowIfEqual(value, other) value == other none (uses EqualityComparer<T>.Default)
ThrowIfNotEqual(value, other) value != other none (uses EqualityComparer<T>.Default)
ThrowIfLessThan(value, other) value < other IComparable<T>
ThrowIfLessThanOrEqual(value, other) value <= other IComparable<T>
ThrowIfGreaterThan(value, other) value > other IComparable<T>
ThrowIfGreaterThanOrEqual(value, other) value >= other IComparable<T>

So decimal, TimeSpan, DateOnly, string and your own types all work:

Try(() => ArgumentOutOfRangeException.ThrowIfZero(0m, "amount"));
Try(() => ArgumentOutOfRangeException.ThrowIfEqual("admin", "admin", "role"));
Try(() => ArgumentOutOfRangeException.ThrowIfNotEqual(3, 4, "version"));
Try(() => ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(
    new DateOnly(2027, 1, 1), new DateOnly(2026, 12, 31), "date"));
Try(() => ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(TimeSpan.Zero, TimeSpan.Zero, "timeout"));

static void Try(Action a)
{
    try { a(); }
    catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); }
}
amount ('0') must be a non-zero value. (Parameter 'amount')
Actual value was 0.
role ('admin') must not be equal to 'admin'. (Parameter 'role')
Actual value was admin.
version ('3') must be equal to '4'. (Parameter 'version')
Actual value was 3.
date ('1/1/2027') must be less than '12/31/2026'. (Parameter 'date')
Actual value was 1/1/2027.
timeout ('00:00:00') must be greater than '00:00:00'. (Parameter 'timeout')
Actual value was 00:00:00.

This example passes literals, so it gives the names explicitly. Without them the parameter name would be the literal text, such as 0m. Values in the message are formatted with the current culture (this ran under en-US).

ObjectDisposedException.ThrowIf

A disposable class should refuse to work after Dispose. ObjectDisposedException.ThrowIf(condition, instance) (.NET 7) replaces the usual if (_disposed) throw new ObjectDisposedException(GetType().FullName):

var log = new LogWriter();
log.Write("first");
log.Dispose();
try
{
    log.Write("second");
}
catch (ObjectDisposedException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
    Console.WriteLine($"ObjectName = {e.ObjectName}");
}

sealed class LogWriter : IDisposable
{
    private bool _disposed;

    public void Write(string message)
    {
        ObjectDisposedException.ThrowIf(_disposed, this);
        Console.WriteLine($"log: {message}");
    }

    public void Dispose() => _disposed = true;
}
log: first
ObjectDisposedException: Cannot access a disposed object.
Object name: 'LogWriter'.
ObjectName = LogWriter

The object name comes from the instance's type. There is also an overload that takes a Type, for static code or when you don't want to pass this.

Writing your own guards with [CallerArgumentExpression]

The built-in helpers cover the common cases. For anything else you can write your own guard, and it gets the parameter name for free in the same way. Put [CallerArgumentExpression("otherParam")] on an optional string? parameter, and the compiler passes the source text of the argument given for otherParam:

using System.Runtime.CompilerServices;

int start = 10, end = 5;
string[] tags = ["a", "b"];

Show(start <= end);
Show(tags.Length > 0 && tags.All(t => t.Length > 1));
Show(Math.Max(start,
              end) /* biggest */ == 10);
Show(true, "explicit text");

static void Show(bool value, [CallerArgumentExpression(nameof(value))] string? expression = null)
    => Console.WriteLine($"{expression} => {value}");
start <= end => False
tags.Length > 0 && tags.All(t => t.Length > 1) => False
Math.Max(start,
              end) /* biggest */ == 10 => True
explicit text => True

The captured text is the argument exactly as written in the source, including line breaks and comments. If the caller passes the parameter explicitly, that value wins. Test frameworks use the same trick to print the failing expression in assertion messages.

A small Guard class

The built-in helpers return void. That's fine as a statement, but it doesn't work inside an expression, such as a property initializer. A guard that returns the validated value fits there. Here it is used to validate primary constructor parameters, where there is no constructor body to put if statements in:

using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;

var ok = new Account("ACC-1", 500m);
Console.WriteLine($"{ok.Id}: limit {ok.Limit}");

Try(() => new Account("  ", 500m));
Try(() => new Account("ACC-2", -1m));
Try(() => Book(new DateOnly(2026, 5, 10), new DateOnly(2026, 5, 3)));

static void Book(DateOnly from, DateOnly to)
{
    Guard.That(from <= to);
    Console.WriteLine($"booked {from} - {to}");
}

static void Try(Action a)
{
    try { a(); }
    catch (ArgumentException e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); }
}

class Account(string id, decimal limit)
{
    public string Id { get; } = Guard.NotBlank(id);
    public decimal Limit { get; } = Guard.Positive(limit);
}

static class Guard
{
    public static T NotNull<T>([NotNull] T? value,
        [CallerArgumentExpression(nameof(value))] string? paramName = null) where T : class
        => value ?? throw new ArgumentNullException(paramName);

    public static string NotBlank([NotNull] string? value,
        [CallerArgumentExpression(nameof(value))] string? paramName = null)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(value, paramName);
        return value;
    }

    public static T Positive<T>(T value,
        [CallerArgumentExpression(nameof(value))] string? paramName = null) where T : INumberBase<T>
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value, paramName);
        return value;
    }

    public static void That([DoesNotReturnIf(false)] bool condition,
        [CallerArgumentExpression(nameof(condition))] string? expression = null)
    {
        if (!condition)
            throw new ArgumentException($"Argument check failed: {expression}");
    }
}
ACC-1: limit 500
ArgumentException: The value cannot be an empty string or composed entirely of whitespace. (Parameter 'id')
ArgumentOutOfRangeException: limit ('-1') must be a non-negative and non-zero value. (Parameter 'limit')
Actual value was -1.
ArgumentException: Argument check failed: from <= to

Some details:

#nullable enable
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

Console.WriteLine(Length1("abc"));
Console.WriteLine(Length2("abc"));

static int Length1(string? s)
{
    MyThrowIfNull(s);
    return s.Length;
}

static int Length2(string? s)
{
    MyThrowIfNullAnnotated(s);
    return s.Length;
}

static void MyThrowIfNull(object? value, [CallerArgumentExpression(nameof(value))] string? name = null)
{
    if (value is null) throw new ArgumentNullException(name);
}

static void MyThrowIfNullAnnotated([NotNull] object? value, [CallerArgumentExpression(nameof(value))] string? name = null)
{
    if (value is null) throw new ArgumentNullException(name);
}

dotnet build app.cs warns only about the version without the annotation:

app.cs(11,12): warning CS8602: Dereference of a possibly null reference.

For a single null check in an initializer you don't need a helper at all: public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name)); is a throw expression. It just brings nameof back.

Using CallerArgumentExpression on older targets

The attribute type ships with .NET Core 3.0 and later, but the feature is in the compiler (C# 10), which looks for the attribute by name. A library that targets netstandard2.0 or .NET Framework can declare its own internal copy and set <LangVersion>10</LangVersion> or later:

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    internal sealed class CallerArgumentExpressionAttribute : Attribute
    {
        public CallerArgumentExpressionAttribute(string parameterName)
            => ParameterName = parameterName;

        public string ParameterName { get; }
    }
}

The callers' compiler must be C# 10 or newer too, otherwise they just get the default null. Packages such as PolySharp generate this and other such attributes for you. The throw helpers themselves don't exist on older frameworks, so write your own as shown above.

Pitfalls

The captured name is whatever you passed

ThrowIfX(expr) reports expr, which isn't always a parameter name. If you validate a value derived from a parameter, give the real name:

Try(() => RenameWrong("      "));
Try(() => Rename("      "));
Try(() => Rename("   bob   "));

static void RenameWrong(string newName)
{
    ArgumentNullException.ThrowIfNull(newName);
    string trimmed = newName.Trim();
    ArgumentException.ThrowIfNullOrEmpty(trimmed); // reports 'trimmed'
    Console.WriteLine($"renamed to '{trimmed}'");
}

static void Rename(string newName)
{
    ArgumentNullException.ThrowIfNull(newName);
    string trimmed = newName.Trim();
    ArgumentException.ThrowIfNullOrEmpty(trimmed, nameof(newName));
    Console.WriteLine($"renamed to '{trimmed}'");
}

static void Try(Action a)
{
    try { a(); }
    catch (ArgumentException e) { Console.WriteLine(e.Message); }
}
The value cannot be an empty string. (Parameter 'trimmed')
The value cannot be an empty string. (Parameter 'newName')
renamed to 'bob'

A caller who reads (Parameter 'trimmed') has no idea what that refers to. nameof is still the right tool in this case.

Iterators and async methods check late

In an iterator (a method with yield return), no code runs until the caller starts enumerating, and that includes your guard clauses. The fix is to validate in a normal method that returns a nested iterator:

IEnumerable<string> lines;
try
{
    lines = ReadLines(null!);
    Console.WriteLine("ReadLines returned without throwing");
    foreach (var line in lines) Console.WriteLine(line);
}
catch (ArgumentNullException e) { Console.WriteLine($"thrown during foreach: {e.ParamName}"); }

try
{
    lines = ReadLinesFixed(null!);
    Console.WriteLine("not reached");
}
catch (ArgumentNullException e) { Console.WriteLine($"thrown at the call: {e.ParamName}"); }

static IEnumerable<string> ReadLines(TextReader reader)
{
    ArgumentNullException.ThrowIfNull(reader);
    while (reader.ReadLine() is { } line)
        yield return line;
}

static IEnumerable<string> ReadLinesFixed(TextReader reader)
{
    ArgumentNullException.ThrowIfNull(reader);
    return Iterate(reader);

    static IEnumerable<string> Iterate(TextReader reader)
    {
        while (reader.ReadLine() is { } line)
            yield return line;
    }
}
ReadLines returned without throwing
thrown during foreach: reader
thrown at the call: reader

An async method behaves similarly. The guard runs right away, but the exception is stored in the returned task and only thrown when someone awaits it:

var task = SaveAsync(null!);
Console.WriteLine($"SaveAsync returned, task status: {task.Status}");
try { await task; }
catch (ArgumentNullException e) { Console.WriteLine($"thrown at await: {e.ParamName}"); }

static async Task SaveAsync(string path)
{
    ArgumentNullException.ThrowIfNull(path);
    await Task.Delay(10);
}
SaveAsync returned, task status: Faulted
thrown at await: path

Usually that's fine, because the caller awaits right away. If you need the exception at the call itself, use the same split: a non-async method that validates and then returns the task from an async local function.

Validation is not error handling for user input

Argument exceptions mean "the caller has a bug". Don't catch ArgumentException to validate form fields or file contents. Check those values and report the problem as part of normal control flow (see Exception Anti-patterns and Best Practices).

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents