Courtesy of a link tweet from Ayende and a blog entry on DevTalk.net, 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.

Comments

blog comments powered by Disqus
Next Post
MoreLINQ  15 Sep 2010
Prior Post
Clean Code  12 Sep 2010
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
Archives
September 2010
2010