Using Validate
The static methods in Validate throw an exception if the value doesn't exist, or sometimes if it doesn't exist in the expected form. They can be used to null-check a parameter in a single line of code without repeating the same few lines throughout your codebase.
If the value does exist, Validate's methods return it untouched - so they can be used for pass-through validation where you wouldn't want to write lines of code at all, such as when passing arguments to a base or chained constructor:
public class ExampleClass : ExampleBaseClass
{
public ExampleClass(string inText)
: base(Validate.ThrowIfNull(inText))
{
}
}
Validate's null-checking methods can be used to resolve Code Analysis warning CA1062: Validate arguments of public methods.
- Validate.ThrowIfNull<T>(T, string)
- Validate.ThrowIfNullOrEmpty<T>(T, string)
- Validate.ThrowIfNullOrEmpty(string, string)
- Validate.ThrowIfNullOrEmpty(string, string, bool)
- Validate.ThrowIfNullOrWhiteSpace(string, string)
The following methods won't resolve CA1062, but may also be useful:
- Validate.ThrowIf<T>(Predicate<T>, T, string, string, params object[])
- Validate.ThrowIfNot<T>(Predicate<T>, T, string, string, params object[])
- Validate.ThrowIfEqualTo<T>(T, T, string)
- Validate.ThrowIfGreaterThan<T>(T, T, string)
- Validate.ThrowIfGreaterThanOrEqualTo<T>(T, T, string)
- Validate.ThrowIfLessThan<T>(T, T, string)
- Validate.ThrowIfLessThanOrEqualTo<T>(T, T, string)
- Validate.ThrowIfEmptyGuid(Guid, string)
- Validate.ThrowIfNotOfType<T>(object, string)
- Validate.ThrowIfNotOfType(type, object, string)