Guest User

Untitled

a guest
Dec 11th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. public struct Maybe<T> where T : class
  2. {
  3. private readonly T _value;
  4.  
  5. public T Value
  6. {
  7. get
  8. {
  9. if (HasNoValue)
  10. throw new InvalidOperationException();
  11. return _value;
  12. }
  13. }
  14.  
  15. public bool HasValue => _value != null;
  16.  
  17. public bool HasNoValue => !HasValue;
  18.  
  19. private Maybe(T value)
  20. {
  21. _value = value;
  22. }
  23.  
  24. public static implicit operator Maybe<T>(T value)
  25. {
  26. return new Maybe<T>(value);
  27. }
  28.  
  29. public static bool operator ==(Maybe<T> maybe, T value)
  30. {
  31. if (maybe.HasNoValue)
  32. return false;
  33.  
  34. return maybe.Value.Equals(value);
  35. }
  36.  
  37. public static bool operator !=(Maybe<T> maybe, T value)
  38. {
  39. return !(maybe == value);
  40. }
  41.  
  42. public static bool operator ==(Maybe<T> first, Maybe<T> second)
  43. {
  44. return first.Equals(second);
  45. }
  46.  
  47. public static bool operator !=(Maybe<T> first, Maybe<T> second)
  48. {
  49. return !(first == second);
  50. }
  51.  
  52. public bool Equals(Maybe<T> other)
  53. {
  54. if (HasNoValue && other.HasNoValue)
  55. return true;
  56.  
  57. if (HasNoValue || other.HasNoValue)
  58. return false;
  59.  
  60. return _value.Equals(other._value);
  61. }
  62.  
  63. public override int GetHashCode()
  64. {
  65. return _value.GetHashCode();
  66. }
  67.  
  68. public override string ToString()
  69. {
  70. if (HasNoValue)
  71. return "No Value";
  72. return Value.ToString();
  73. }
  74.  
  75. public T Unwrap(T defaultValue = default(T))
  76. {
  77. if (HasValue)
  78. return Value;
  79.  
  80. return defaultValue;
  81. }
  82. }
Add Comment
Please, Sign In to add comment