Monday, July 20, 2009 9:36 PM
blambert
Useful extension method for the object type…
Here’s a useful extension method for the object type:
/// <summary>
/// Extends object to have a ValidateArgumentNotNull method.
/// </summary>
/// <remarks>
/// Validates that an object is not null. If the object is null,
/// ArgumentNullException will be thrown.
/// </remarks>
/// <param name="value">The object being extended.</param>
/// <param name="argumentmName">The argument name.</param>
public static void ValidateArgumentNotNull(this object value, string argumentmName)
{
if (value == null)
{
throw new ArgumentNullException(argumentmName);
}
}
A little piece of syntactic sugar to turn N lines of boilerplate code like this:
if (foo == null)
{
throw new ArgumentNullException("foo");
}
if (bar == null)
{
throw new ArgumentNullException("bar");
}
if (foobar == null)
{
throw new ArgumentNullException("foobar");
}
Into something tighter, that you (sort of) just IntelliSense through:
foo.ValidateArgumentNotNull("foo");
bar.ValidateArgumentNotNull("bar");
foobar.ValidateArgumentNotNull("foobar");
I want to know if I can find the parameter name out through reflection, so I don’t have to pass it in. That would be the ultimate in tightness.
Best,
Brian