Validating Arguments 

The following guidelines help ensure that you validate arguments correctly.

Do validate arguments passed to public, protected, or explicitly implemented members. Throw System.ArgumentException, or one of its derived classes, if the validation fails.

This guideline does not require that the validation code be in the publicly visible member. It is acceptable to pass the arguments to an internal method that handles the validation.

Do throw System.ArgumentNullException if a null argument is passed but the member does not support null (Nothing in Visual Basic) arguments.

Do validate enumeration parameters.

You cannot assume that enumeration arguments are values defined in the enumeration because the common language runtime (CLR) supports casting any integer value to an enumeration value regardless of whether the value is defined in the enumeration.

Do not use System.Enum.IsDefined(System.Type,System.Object) for enumeration range checks as it is based on the runtime type of the enumeration, which can change from version to version.

A later version of a library can add values to a shipping enumeration. Using IsDefined for data validation can be dangerous because existing code (which did not handle the new value) will treat the new value as valid input because IsDefined returns true for the new value. Check that the input is in the range of values your program can support and throw an exception if it is not.

Do be aware that mutable arguments passed may have changed after they were validated.

If the member is security-sensitive, make a private copy of the mutable object and use the copy for validation and processing. This applies only to mutable data. Immutable data, such as Uri objects, does not need to be copied.

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also


Parameter Design

Other Resources

Member Design Guidelines
Design Guidelines for Developing Class Libraries