Parameter Validation Using ArgumentExceptions

In the latest .NET versions, argument validation has been streamlined with new helper extension methods that make it even easier and more expressive to throw argument exceptions. Some of these methods were first introduced in .NET 6 but have been enhanced with subsequent releases. Here are some of the latest ways to handle argument validation in .NET 8:

Throw if Argument is Null or Empty:

void Foo(string bar)
{
    ArgumentException.ThrowIfNullOrEmpty(bar, nameof(bar));
}

Throw if Argument is Null:

void Foo(object obj) 
{
    ArgumentNullException.ThrowIfNull(obj, nameof(obj));
}

Throw if Argument is Null or Whitespace:

void Foo(string bar) 
{
    ArgumentException.ThrowIfNullOrWhiteSpace(bar, nameof(bar));
}

Throw if Argument is Out of Range:
There are various methods for checking range values for integers and other number types: minimums, maximums, inclusive, exclusive, etc. This is one example, but check the ArgumentOutOfRangeException documentation for all of the other options.

void Foo(int number)
{
    ArgumentOutOfRangeException.ThrowIfOutOfRange(number, 0, int.MaxValue, nameof(number));
}

These methods help to reduce boilerplate code and enhance readability. Here’s how they are used:

  • ArgumentException.ThrowIfNullOrEmpty: Throws an ArgumentException if the string is null or empty.
  • ArgumentNullException.ThrowIfNull: Throws an ArgumentNullException if the argument is null.
  • ArgumentException.ThrowIfNullOrWhiteSpace: Throws an ArgumentException if the string is null, empty, or consists only of white-space characters.
  • ArgumentOutOfRangeException.ThrowIfOutOfRange: Throws an ArgumentOutOfRangeException if the value is outside the specified range.

Your earlier versions of .NET error checking, your code may have looked like the following:

void Foo(string bar)
{
    if (string.IsNullOrWhitespace(bar))
    {
        throw new ArgumentException("Argument cannot be null or whitespace", nameof(bar));
    }
}

void Foo(int number)
{
    if (number < 0)
    {
        throw new ArgumentOutOfRangeException(nameof(number), "Number cannot be negative");
    }
}

But now you can reduce that checking code and make your whole method much more readable.

There are multiple ways to handle parameter validation. And you don’t always use exceptions to do that. There are times when data validation and returning Result objects (we’ll discuss those in future posts) provide better control flow for your API or application. But, when you are going to validate some internal state via exceptions, then the ArgumentException extension methods are the way to go.

Leave a comment