Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Argument Validation

The book sample code commonly uses a custom ArgumentValidator class to ensure that method arguments are not null or fall within a valid range. This allows a method to fail fast, rather than continuing and raising a more difficult to diagnose error.

You frequently see statements like the following at the beginning of a method:

string PerformSomeAction(string value)
{
    stringField = ArgumentValidator.AssertNotNull(value, "value");
...
}

Here, if value is null, then an ArgumentNullException is thrown. If not null, then the stringField field is set to the value in a fluent manner.

All the ArgumentValidator methods are fluent; they return the value passed to them so that they can be assigned to local variables or fields in a single statement.

The ArgumentValidator.AssertNotNull method is as follows:

public static T AssertNotNull<T>(T value, string parameterName) where T : class
{
    if (value == null)
    {
        throw new ArgumentNullException(parameterName);
    }

    return value;
}

ArgumentValidator contains various other assertion methods for strings and numeric values. Some are briefly discussed.

ArgumentValidator allows you to assert that an argument falls within a particular range. The following AssertLessThan method ensures that the value is less than a certain value:

public static double AssertLessThan(
    double comparisonValue, double value, string parameterName)
{
    if (value >= comparisonValue)
    {
        throw new ArgumentOutOfRangeException(
            "Parameter should be less than "
            + comparisonValue, parameterName);
    }
    return value;
}

This then allows you to validate that a numeric value is less than, for example, 1:

ArgumentValidator.AssertLessThan(1, value, "value");

Other methods, such as AssertNotNullAndOfType, allow you to raise an exception if an argument is null or not of the expected type, and AssertNotNullOrWhiteSpace accepts a string and raises an ArgumentException if string.IsNullOrWhiteSpace(value) returns true.

  • + Share This
  • 🔖 Save To Your Account