Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Maybe<T>
- {
- private readonly IEnumerable<T> values;
- public T Value
- {
- get
- {
- if (!this.HasValue)
- {
- throw new InvalidOperationException(String.Format("Accessing Maybe<{0}>.Value when there is no value. Try the Maybe<{0}>.ValueOrDefault({0}).", typeof(T)));
- }
- var result = this.values.First();
- return result;
- }
- }
- public bool HasValue
- {
- get
- {
- var result = this.values.Any();
- return result;
- }
- }
- public Maybe()
- {
- this.values = new T[0];
- }
- public Maybe(T value)
- {
- this.values = IsNull(value) ? new T[0] : new[] { value };
- }
- public T ValueOrDefault(T defaultValue)
- {
- var result = this.HasValue ? Value : defaultValue;
- return result;
- }
- public Type GetValueType()
- {
- var result = typeof(T);
- return result;
- }
- public override int GetHashCode()
- {
- return HasValue ? Value.GetHashCode() : 0;
- }
- public override string ToString()
- {
- return HasValue ? Value.ToString() : "";
- }
- public static implicit operator Maybe<T>(T value)
- {
- var result = new Maybe<T>(value);
- return result;
- }
- public static explicit operator T(Maybe<T> value)
- {
- var result = value.Value;
- return result;
- }
- private bool IsNull(T value)
- {
- var result = default(T) == null && value == null;
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement