Checking arguments of a method

If you are not using the Argument class, you are definitely missing something! It allows you to check for a method input and make sure it is valid. So, instead of writing this:

public void DoSomething(string myInput)
{
    if (string.IsNullOrWhitespace(myInput)
    {
        Log.Error("Argument 'myInput' cannot be null or whitespace");
        throw new ArgumentException("Argument 'myInput' cannot be null or whitespace", "myInput");
    }

    // custom logic
}

You can write this:

public void DoSomething(string myInput)
{
    Argument.IsNotNullOrWhitespace(() => myInput);

    // custom logic
}

However, when you are writing lots of code, then even this piece of code can be too much. Thanks to the Catel.Resharper plugin, it is possible to select the argument (in this case myInput), hit ALT + Enter and generate the code, just like the video below:

Below is a table what argument checks are available per type:

.NET Type

Available checks

Exception type

Constraint text

Any reference type

IsNotNull

ArgumentNullException

The <paramref name="[paramname]"/> is <c>null</c>

ImplementsInterface

ArgumentException

The <paramref name="[paramname]"/> does not implement the <see cref=”[interface]” /> interface

IsOfType

ArgumentException

The <paramref name="[paramname]"/> is not of type <see cref=”[type]” />

Array

IsNotNullOrEmptyArray

ArgumentException

The <paramref name="[paramname]"/> is <c>null</c> or an empty array

Int / decimal / double / float

IsNotOutOfRange

ArgumentOutOfRangeException

The <paramref name="[paramname]"/> is not between <c>[min]</c> and <c>[max]</c>

IsMinimal

ArgumentOutOfRangeException

The <paramref name="[paramname]"/> is smaller than <c>[value]</c>

IsMaximal

ArgumentOutOfRangeException

The <paramref name="[paramname]"/> is larger than <c>[value]</c>

String

IsNotNullOrEmpty

ArgumentException

The <paramref name="[paramname]"/> is <c>null</c> or empty

IsNotNullOrWhitespace

ArgumentException

The <paramref name="[paramname]"/> is <c>null</c> or whitespace

IsMatch

ArgumentException

The <paramref name="[paramname]"/> doesn’t match with pattern <c><![CDATA[[pattern]]]></c>.

IsNotMatch

ArgumentException

The <paramref name="[paramname]"/> does match with pattern <c><![CDATA[[pattern]]]></c>.

Guid

IsNotNullOrEmpty

ArgumentException

The <paramref name="[paramname]"/> is <c>null</c> or empty

Type

ImplementsInterface

ArgumentException

The <paramref name="[paramname]"/> does not implement the <see cref=”[interface]” /> interface

IsOfType

ArgumentException

The <paramref name="[paramname]"/> is not of type <see cref=”[type]” />