Skip to content

Instantly share code, notes, and snippets.

@kmorcinek
Created April 2, 2014 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmorcinek/9931393 to your computer and use it in GitHub Desktop.
Save kmorcinek/9931393 to your computer and use it in GitHub Desktop.
Chained null checks and the Maybe monad & others
using System;
public static class ObjectExtensions
{
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);
}
public static TResult Return<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator, TResult failureValue)
where TInput : class
{
if (o == null) return failureValue;
return evaluator(o);
}
public static TInput If<TInput>(this TInput o, Func<TInput, bool> evaluator)
where TInput : class
{
if (o == null) return null;
return evaluator(o) ? o : null;
}
public static TInput Unless<TInput>(this TInput o, Func<TInput, bool> evaluator)
where TInput : class
{
if (o == null) return null;
return evaluator(o) ? null : o;
}
public static TInput Do<TInput>(this TInput o, Action<TInput> action)
where TInput : class
{
if (o == null) return null;
action(o);
return o;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment