Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. public class Maybe<T>
  2. {
  3. private readonly IEnumerable<T> values;
  4.  
  5. public T Value
  6. {
  7. get
  8. {
  9. if (!this.HasValue)
  10. {
  11. throw new InvalidOperationException(String.Format("Accessing Maybe<{0}>.Value when there is no value. Try the Maybe<{0}>.ValueOrDefault({0}).", typeof(T)));
  12. }
  13.  
  14. var result = this.values.First();
  15. return result;
  16. }
  17. }
  18.  
  19. public bool HasValue
  20. {
  21. get
  22. {
  23. var result = this.values.Any();
  24. return result;
  25. }
  26. }
  27.  
  28. public Maybe()
  29. {
  30. this.values = new T[0];
  31. }
  32.  
  33. public Maybe(T value)
  34. {
  35. this.values = IsNull(value) ? new T[0] : new[] { value };
  36. }
  37.  
  38.  
  39. public T ValueOrDefault(T defaultValue)
  40. {
  41. var result = this.HasValue ? Value : defaultValue;
  42. return result;
  43. }
  44.  
  45. public Type GetValueType()
  46. {
  47. var result = typeof(T);
  48. return result;
  49. }
  50.  
  51. public override int GetHashCode()
  52. {
  53. return HasValue ? Value.GetHashCode() : 0;
  54. }
  55.  
  56. public override string ToString()
  57. {
  58. return HasValue ? Value.ToString() : "";
  59. }
  60.  
  61. public static implicit operator Maybe<T>(T value)
  62. {
  63. var result = new Maybe<T>(value);
  64. return result;
  65. }
  66.  
  67. public static explicit operator T(Maybe<T> value)
  68. {
  69. var result = value.Value;
  70. return result;
  71. }
  72.  
  73. private bool IsNull(T value)
  74. {
  75. var result = default(T) == null && value == null;
  76. return result;
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement