Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to extend null check?

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?

like image 563
AgentFire Avatar asked Jul 17 '12 12:07

AgentFire


People also ask

Can you call an extension method on a null object?

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.

Should extension methods check for NULL?

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.


1 Answers

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.

like image 95
Adam Houldsworth Avatar answered Sep 20 '22 18:09

Adam Houldsworth