skip to content

In C#, what do `ArgumentNullException.ThrowIfNull` and the other guard helpers throw, and where does the parameter name in the exception come from?

level: middleimportance: should knowfreq 45%

answer

  1. one line per argument check
  2. null versus empty versus out of range
  3. the compiler fills the last parameter
  4. source text, not the declared name

basics

~20 s

ThrowIfNull throws ArgumentNullException when its argument is null; the string helpers add ArgumentException for empty or whitespace, and the range helpers throw ArgumentOutOfRangeException. A [CallerArgumentExpression] parameter makes the compiler pass the argument's source text as ParamName.

solid answer

~30 s

`ArgumentNullException.ThrowIfNull(object? argument, string? paramName = null)` throws `ArgumentNullException` when `argument` is null. `ArgumentException.ThrowIfNullOrEmpty` and `ThrowIfNullOrWhiteSpace` throw `ArgumentNullException` for null and `ArgumentException` for an empty or whitespace string. `ArgumentOutOfRangeException` has `ThrowIfNegative`, `ThrowIfZero`, `ThrowIfNegativeOrZero`, `ThrowIfGreaterThan`, `ThrowIfLessThan` and friends. All are in .NET 8. Their `paramName` parameter carries `[CallerArgumentExpression]`, a C# 10 feature, so the compiler passes the text of the argument expression: `ThrowIfNull(payment.Payer)` reports `payment.Payer`. The `[NotNull]` annotation lets nullable analysis treat the argument as non-null afterwards. The analyzer rules CA1510 to CA1513 suggest these helpers over hand-written `if` checks, and CA2264 warns when the value can never be null.

code

csharp · 26 lines
csharp
Try(() => Payments.Queue(new Payment(null, "INV-7", 10m)));
Try(() => Payments.Queue(new Payment(new Payer("  "), "INV-7", 10m)));
Try(() => Payments.Queue(new Payment(new Payer("ACME"), "INV-7", -5m)));

static void Try(Action a)
{
    try { a(); }
    catch (ArgumentException ex)
    {
        Console.WriteLine($"{ex.GetType().Name} | ParamName = {ex.ParamName}");
    }
}

record Payer(string AccountId);
record Payment(Payer? Payer, string InvoiceId, decimal Amount);

static class Payments
{
    public static void Queue(Payment payment)
    {
        ArgumentNullException.ThrowIfNull(payment);
        ArgumentNullException.ThrowIfNull(payment.Payer);
        ArgumentException.ThrowIfNullOrWhiteSpace(payment.Payer.AccountId);
        ArgumentOutOfRangeException.ThrowIfNegative(payment.Amount);
    }
}

go deeper

for a junior

Recall ThrowIfNull for null arguments and that it saves writing an if with throw new ArgumentNullException(nameof(x)).

for a middle

Explain which exception each helper throws, that CallerArgumentExpression fills ParamName with the argument's source text, and the [NotNull] effect on nullable analysis.

for a senior

Point out the traps: nested expressions as names, forwarding paramName from a wrapper, CA2264 on value types, and guards that run late in deferred methods.

for a principal

Make guard helpers the team default by raising CA1510 to CA1513 above suggestion, and agree that they check arguments, not object state.

## The guard helpers A **guard clause** checks an argument at the top of a method and throws if the caller broke the method's contract. .NET ships static helpers on the exception types themselves, so each check is one line: | Helper | Throws when | Exception type | |---|---|---| | `ArgumentNullException.ThrowIfNull(argument)` | `argument` is null | `ArgumentNullException` | | `ArgumentException.ThrowIfNullOrEmpty(text)` | null, or `""` | `ArgumentNullException` for null, `ArgumentException` for empty | | `ArgumentException.ThrowIfNullOrWhiteSpace(text)` | null, empty, or only whitespace | `ArgumentNullException` for null, `ArgumentException` otherwise | | `ArgumentOutOfRangeException.ThrowIfNegative(value)` | `value` is below zero | `ArgumentOutOfRangeException` | | `ArgumentOutOfRangeException.ThrowIfZero` / `ThrowIfNegativeOrZero` | zero, or zero or below | `ArgumentOutOfRangeException` | | `ArgumentOutOfRangeException.ThrowIfGreaterThan(value, other)` and the `LessThan`, `Equal`, `NotEqual` variants | the comparison holds | `ArgumentOutOfRangeException` | All of them are available in .NET 8, the previous long-term-support release. The numeric helpers are generic: `ThrowIfNegative<T>` and `ThrowIfZero<T>` require `T : INumberBase<T>`, while `ThrowIfGreaterThan<T>`, `ThrowIfLessThan<T>` and their `OrEqual` forms require `T : IComparable<T>`, and `ThrowIfEqual<T>` and `ThrowIfNotEqual<T>` take any `T`; `int`, `decimal` and `double` satisfy all of them. Because `ArgumentNullException` and `ArgumentOutOfRangeException` both derive from `ArgumentException`, a caller's `catch (ArgumentException)` sees all three. ## What they replace Before the helpers, a guard was an `if` with a `throw` and a `nameof`: `if (payment is null) throw new ArgumentNullException(nameof(payment));`. C# 7 added **throw expressions**, which made assignments shorter: `_payer = payer ?? throw new ArgumentNullException(nameof(payer));`. Both still work and both repeat the parameter name by hand, which drifts when a parameter is renamed without its `nameof`, or when someone copies the line to another parameter and forgets to update it. The helpers remove that duplication, and the throw expression remains useful when you want to assign and check in one statement. ## How the parameter name gets filled Each helper's last parameter is declared like this in the reference source: `[CallerArgumentExpression(nameof(argument))] string? paramName = null` `CallerArgumentExpression`, added in **C# 10**, tells the compiler: when the caller omits `paramName`, pass the **source text** of the expression supplied for `argument`. Three consequences follow: - `ThrowIfNull(payment)` reports `payment`, so you never repeat `nameof(payment)`. - `ThrowIfNull(payment.Payer)` reports `payment.Payer`, the expression as written, not a declared parameter name. On .NET 10 the code example printed `ParamName = payment.Payer`, and the exception's message read `Value cannot be null. (Parameter 'payment.Payer')`. - If you forward a check from a helper of your own, pass `paramName` explicitly, or the exception reports the helper's local expression instead of your caller's parameter. Writing your own methods with `[CallerArgumentExpression]` is a topic about attributes; here it matters only because it explains the name in the exception. ## What the helpers add over a hand-written check - **Less code, consistent messages.** The helpers build standard messages such as `payment.Amount ('-5') must be a non-negative value.` - **Smaller callers.** The throw sits in a separate helper method, which the CA1510 documentation says keeps argument checks from bloating small methods and blocking inlining. - **Flow analysis.** `ThrowIfNull`, `ThrowIfNullOrEmpty` and `ThrowIfNullOrWhiteSpace` mark the argument `[NotNull]`, so after the call the compiler's nullable analysis treats it as non-null and stops warning. - **Analyzer support.** CA1510, CA1511, CA1512 and CA1513 suggest replacing `if (...) throw new ...` with the matching helper, the last one for `ObjectDisposedException.ThrowIf`, which belongs to disposal. ## Traps 1. **Value types.** `ThrowIfNull` takes `object?`, so passing a non-nullable struct boxes it and can never throw; the SDK reported **CA2264**, "Calling 'ArgumentNullException.ThrowIfNull' and passing a non-nullable value is a no-op". For a nullable struct such as `int?`, **CA1871** suggests checking `HasValue` instead, to avoid the box. 2. **Wrong exception for state.** The helpers are for **arguments**. If the object itself is in the wrong state, throw `InvalidOperationException`; which exception fits which failure is a question of exception design. 3. **Deferred methods.** In an iterator, a guard written in the body runs only when enumeration starts; in an `async` method it runs at the call, but its exception is stored in the returned task instead of reaching the caller directly. Splitting the check from the deferred part is covered with local functions. ## Putting them in a payment method The code example guards `Payments.Queue(Payment payment)` with four lines: the payment, its payer, the payer's account id and the amount. A missing payer, a whitespace account id and a negative amount each produce the specific exception type with a `ParamName` that points at the exact expression the caller got wrong.

  • What does `ArgumentException.ThrowIfNullOrEmpty(accountId)` throw for null, and what for an empty string?
    For null it throws `ArgumentNullException`; for `""` it throws `ArgumentException`. Both carry `ParamName = "accountId"`. The reference source first calls `ArgumentNullException.ThrowIfNull` and only then throws the plain `ArgumentException`, so a caller can tell the two cases apart by type.
  • You wrap `ThrowIfNull` in your own `Require(object? value)` helper. Why do the exceptions now report the wrong name?
    `CallerArgumentExpression` captures the expression at the call site of `ThrowIfNull`, which is now inside `Require`, so every exception reports `value`. Give `Require` its own `[CallerArgumentExpression(nameof(value))] string? paramName = null` parameter and pass `paramName` through to `ThrowIfNull`.

  • ThrowIfNull reports the declared parameter name found through reflection
  • ThrowIfNullOrWhiteSpace throws ArgumentNullException for a whitespace string
  • ThrowIfNull on an int is a cheap, harmless safety check
  • you should always pass nameof(x) as the second argument
  • guard helpers are also the right tool for invalid object state