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?
The extension method will get a null parameter. Yes, an exception will be thrown if the method tries to access the object without first testing if it is null. A guy here wrote “IsNull” and “IsNotNull” extension methods that check is the reference passed null or not.
As extension methods are in reality static methods of another class, they work even if the reference is null . This can be utilized to write utility methods for various cases.
I tend to stick to the ubiquitous Guard
class for this:
static class Guard
{
public static void AgainstNulls(object parameter, string name = null)
{
if (parameter == null)
throw new ArgumentNullException(name ?? "guarded argument was null");
Contract.EndContractBlock(); // If you use Code Contracts.
}
}
Guard.AgainstNulls(parameter, "parameter");
And shy away from extending object
, plus to the naked eye a method call on a null
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 the class
constraint blocks it.
Our Guard
class also has the Contract.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With