Created
October 11, 2010 17:23
-
-
Save jnericks/620891 to your computer and use it in GitHub Desktop.
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
public static class MaybeExtensions | |
{ | |
public static Maybe<T> ToMaybe<T>(this T input) where T : class | |
{ | |
return new Maybe<T>(input); | |
} | |
public static Maybe<TResult> Get<TInput, TResult>(this Maybe<TInput> maybe, Func<TInput, TResult> func) | |
where TInput : class | |
where TResult : class | |
{ | |
var result = maybe.HasValue ? new Maybe<TResult>(func(maybe.Value)) : Maybe<TResult>.None; | |
return result; | |
} | |
public static Maybe<TInput> If<TInput>(this Maybe<TInput> maybe, Func<TInput, bool> func) where TInput : class | |
{ | |
return maybe.HasValue && func(maybe.Value) | |
? maybe | |
: Maybe<TInput>.None; | |
} | |
public static TResult Return<TInput, TResult>(this Maybe<TInput> maybe, Func<TInput, TResult> func, TResult defaultValue) where TInput : class | |
{ | |
return maybe.HasValue | |
? func(maybe.Value) | |
: defaultValue; | |
} | |
} | |
public sealed class Maybe<T> where T : class | |
{ | |
public static Maybe<T> None = new Maybe<T>(default(T)); | |
public T Value { get; set; } | |
public bool HasValue | |
{ | |
get { return Value != null && !Value.Equals(default(T)); } | |
} | |
public Maybe(T value) | |
{ | |
Value = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment