After
a quick Twitter interaction with
Marc Jacobi I thought I'd post a small set of extension methods I like to use for argument checking:
using System;
using System.Collections.Generic;
using System.Text;
namespace peSHIr.Utilities
{
public static class Guards
{
public static void GuardNull
(this object argument, string argumentName)
{
if (argument == null)
{
throw new ArgumentNullException(
argumentName,
"No object supplied");
}
}
public static void GuardNull
(this string argument, string argumentName)
{
if (String.IsNullOrEmpty(argument))
{
throw new ArgumentNullException(
argumentName,
"No text supplied (or text is empty)");
}
}
public static void GuardZero
(this int argument, string argumentName)
{
if (argument == 0)
{
throw new ArgumentNullException(
argumentName,
"The number zero is not allowed here");
}
}
public static void GuardNull<T>
(this Nullable<T> argument, string argumentName)
where T:struct
{
if (argument.HasValue == false)
{
throw new ArgumentNullException(
argumentName,
"Empty nullable type not allowed here");
}
}
public static void GuardMinimum<T>
(this T argument, T lower, string argumentName)
where T : IComparable<T>
{
if (argument.CompareTo(lower) < 0)
{
throw new ArgumentOutOfRangeException(
argumentName, argument,
string.Format("Minimum allowed: {0}", lower));
}
}
public static void GuardMaximum<T>
(this T argument, T upper, string argumentName)
where T : IComparable<T>
{
if (argument.CompareTo(upper) > 0)
{
throw new ArgumentOutOfRangeException(
argumentName, argument,
string.Format("Maximum allowed: {0}", upper));
}
}
public static void GuardRange<T>
(this T argument, T lower, T upper, string argumentName)
where T : IComparable<T>
{
if (argument.CompareTo(lower) < 0 || argument.CompareTo(upper) > 0)
{
throw new ArgumentOutOfRangeException(
argumentName, argument,
string.Format("Allowed: [{0},{1}]", lower, upper));
}
}
}
}
When you can use
code contracts this is probably preferable. Otherwise, these little extension methods can come in really handy for some general cases.