Kijana Woodard

Software Minimalism


Null Check with Extension Methods

Tuesday, May 18, 2010

I mentioned that I got an idea while writing the post on extension methods. I realized that you can null check using this technique.

It get’s annoying writing this code over and over:

public static void ImportantMethod(string value)
{
    if (value == null)
        throw new ArgumentNullException();
}

I had considered using a NotNull<T> to take care of null checking.

But with extension methods like this:

public static class ObjectExtensionMethods
{
    public static void NullCheck<T>(this T foo)
    {
        NullCheck(foo, string.Empty);
    }

    public static void NullCheck<T>(this T foo, string variableName)
    {
        if (foo == null)
            throw new ArgumentNullException(variableName);
    }

    public static void NullCheck<T>(this T foo, string variableName, string message)
    {
        if (foo == null)
            throw new ArgumentNullException(variableName, message);
    }
}

//usage
public static void ImportantMethod(string value)
{
    value.NullCheck();
}

Much nicer. The overloads can facilitate whatever messaging level you desire.

This is all probably a moot point with Code Contracts in .net 4.0. To get Code Contracts working in VS2010, you have to download the code from DevLabs. That caught me off guard because the code contracts namespace is available by default in VS2010, but the actual code analysis was not.

Still, in the right situations I’d like to work on avoiding null altogether with the Null Object Pattern or immutable classes.



If you see a mistake in the post *or* you want to make a comment, please submit an edit.

You can also contact me and I'll post the comment.

0 Comments...