You all do this:
public void Proc(object parameter)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
// Main code.
}
Jon Skeet once mentioned that he sometimes uses the extension to do this check so you can do just:
parameter.ThrowIfNull("parameter");
So I come of with two implementations of this extension and I don't know which one is the best.
First:
internal static void ThrowIfNull<T>(this T o, string paramName) where T : class
{
if (o == null)
throw new ArgumentNullException(paramName);
}
Second:
internal static void ThrowIfNull(this object o, string paramName)
{
if (o == null)
throw new ArgumentNullException(paramName);
}
What do you think?
I tend to stick to the ubiquitous
Guard
class for this:And shy away from extending
object
, plus to the naked eye a method call on anull
object seems nonsensical (although I know it is perfectly valid to have null method calls against extension methods).As for which is best, I'd use neither. They both have infinite recursion. I'd also not bother guarding the message parameter, make it optionally null. Your first solution will also not support
Nullable<T>
types as theclass
constraint blocks it.Our
Guard
class also has theContract.EndContractBlock()
call after it for when we decide to enable Code Contracts, as it fits the "if-then-throw" structure that is required.This is also a perfect candidate for a PostSharp aspect.
What about using Expression Trees (from Visual Studio Magazine):
}
Used like this:
Second one seems more elegant way of handling the same. In this case you can put restriction on every managed object.
I'd use
internal static void ThrowIfNull<T>(this T o, string paramName) where T : class
. I won't useinternal static void ThrowIfNull(this object o, string paramName)
because it might do boxing.I would do this way to avoid hardcoding parameter names. Tomorrow it can change, and you have more work then:
And call it:
The performance hit is trivial (on my mediocre computer it ran for 100000 times just under 25 ms), much faster than Expression based approach seen typically
One such here. But surely don't use this if you cant afford that much hit..
You can also extend this for properties of objects.
You can cache property values to improve performance further as property names don't change during runtime.
See this question additionally: Resolving a parameter name at runtime