Guest User

Untitled

a guest
Jun 17th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. public static class MaybeExtensions
  2. {
  3. public static Maybe<T> ToMaybe<T>(this T input) where T : class
  4. {
  5. return new Maybe<T>(input);
  6. }
  7.  
  8. public static Maybe<TResult> Get<TInput, TResult>(this Maybe<TInput> maybe, Func<TInput, TResult> func)
  9. where TInput : class
  10. where TResult : class
  11. {
  12. var result = maybe.HasValue ? new Maybe<TResult>(func(maybe.Value)) : Maybe<TResult>.None;
  13. return result;
  14. }
  15.  
  16. public static Maybe<TInput> If<TInput>(this Maybe<TInput> maybe, Func<TInput, bool> func) where TInput : class
  17. {
  18. return maybe.HasValue && func(maybe.Value)
  19. ? maybe
  20. : Maybe<TInput>.None;
  21. }
  22.  
  23. public static TResult Return<TInput, TResult>(this Maybe<TInput> maybe, Func<TInput, TResult> func, TResult defaultValue) where TInput : class
  24. {
  25. return maybe.HasValue
  26. ? func(maybe.Value)
  27. : defaultValue;
  28. }
  29. }
  30.  
  31. public sealed class Maybe<T> where T : class
  32. {
  33. public static Maybe<T> None = new Maybe<T>(default(T));
  34.  
  35. public T Value { get; set; }
  36.  
  37. public bool HasValue
  38. {
  39. get { return Value != null && !Value.Equals(default(T)); }
  40. }
  41.  
  42. public Maybe(T value)
  43. {
  44. Value = value;
  45. }
  46. }
Add Comment
Please, Sign In to add comment