Created
April 2, 2014 10:08
-
-
Save kmorcinek/9931393 to your computer and use it in GitHub Desktop.
Chained null checks and the Maybe monad & others
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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