Share via


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

Comments

  • Anonymous
    July 24, 2009
    The best you could do is:string parameterName = new StackTrace().GetFrame(1).GetMethod().GetParameters()[0].Name;With the following caveats:The "(1)" is purely a magic number -- meaning "not this function, but the one that called it".  However, if that method is simple enough, and you are doing an optimized build, it might be inlined by the compiler (I hit that problem while coming up up this)The "[0]" refers to the position of the parameter in the calling function.  This will have to be passed in, so we've only accomplished changing the parameter from an obvious string, to a cryptic number.There is NO WAY to find out the name of the object passed as "value", since there is no requirement that it have a name:   ("hello" + "world").ValidateArgumentNotNull("??????");is a completely viable method call.
  • Anonymous
    July 30, 2009
    I find it a bit disconcerting to have a method that can be called if the object I'm calling it on is null. I expect that to crash. With extensions methods it doesn't have to crash. Something about this just feels wrong to me.