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
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
More smart-code posts »
September 2010