Courtesy of a link tweet from Ayende and a blog entry on, here’s an interesting way to avoid null checks in code: the .With() extension method.

Since extension methods are really static methods with syntactic sugar, they can check for (and handle) null just like any other parameter value.

This allows you to write the following extension method:

public static TResult With<TInput, TResult>(
    this TInput o, Func<TInput, TResult> evaluator)
    where TResult : class where TInput : class
    if (o == null) 
        return null;
    return evaluator(o);

Why would you want this? Go read Chained null checks and the Maybe monad to find out.


blog comments powered by Disqus