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
Next Post
MoreLINQ  15 Sep 2010
Prior Post
Clean Code  12 Sep 2010
Related Posts
Prefer declarative method names  03 Feb 2018
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
Avoiding the Singleton Pattern  22 Jul 2017
Implementing the Singleton Pattern  15 Jul 2017
Static Analysis tools for the Win  15 Apr 2017
Exception Logging  19 Jan 2016
On the Merits of Simple Code  28 Nov 2015
Semantic Types  27 Sep 2015
Command Line Processing  21 Sep 2014
More smart-code posts »
Related Pages
September 2010 archive