Want more features on Pastebin? Sign Up, it's FREE!
Guest

c# maybe implementation

By: a guest on Oct 27th, 2012  |  syntax: C#  |  size: 1.10 KB  |  views: 47  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.     public struct Maybe<T> where T : class
  2.     {
  3.         T Value;
  4.  
  5.         public static Maybe<T> Just(T t)
  6.         {
  7.             return new Maybe<T>() { Value = t };
  8.         }
  9.  
  10.         public static Maybe<T> Nothing { get { return new Maybe<T>(); } }
  11.  
  12.         public static implicit operator Maybe<T>(T value)
  13.         {
  14.             return new Maybe<T>() { Value = value };
  15.         }
  16.  
  17.         public void Guard(Action<T> valuePresent, Action valueAbsent)
  18.         {
  19.             if (Value != null)
  20.             {
  21.                 if (valuePresent != null)
  22.                     valuePresent(Value);
  23.             }
  24.             else if (valueAbsent != null) valueAbsent();
  25.         }
  26.  
  27.         public TResult Guard<TResult>(Func<T, TResult> valuePresent, Func<TResult> valueAbsent)
  28.         {
  29.             if (Value != null)
  30.             {
  31.                 if (valuePresent != null)
  32.                     return valuePresent(Value);
  33.             }
  34.             else if (valueAbsent != null) return valueAbsent();
  35.             throw new ArgumentException("A Maybe guard case was missing and hit");
  36.         }
  37.     }
clone this paste RAW Paste Data