Created
December 8, 2017 22:18
-
-
Save monica85rodrigues/834c3a5e8c1cb81d028c83b7a814ee3d to your computer and use it in GitHub Desktop.
Maybe struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public struct Maybe<T> where T : class | |
{ | |
private readonly T _value; | |
public T Value | |
{ | |
get | |
{ | |
if (HasNoValue) | |
throw new InvalidOperationException(); | |
return _value; | |
} | |
} | |
public bool HasValue => _value != null; | |
public bool HasNoValue => !HasValue; | |
private Maybe(T value) | |
{ | |
_value = value; | |
} | |
public static implicit operator Maybe<T>(T value) | |
{ | |
return new Maybe<T>(value); | |
} | |
public static bool operator ==(Maybe<T> maybe, T value) | |
{ | |
if (maybe.HasNoValue) | |
return false; | |
return maybe.Value.Equals(value); | |
} | |
public static bool operator !=(Maybe<T> maybe, T value) | |
{ | |
return !(maybe == value); | |
} | |
public static bool operator ==(Maybe<T> first, Maybe<T> second) | |
{ | |
return first.Equals(second); | |
} | |
public static bool operator !=(Maybe<T> first, Maybe<T> second) | |
{ | |
return !(first == second); | |
} | |
public bool Equals(Maybe<T> other) | |
{ | |
if (HasNoValue && other.HasNoValue) | |
return true; | |
if (HasNoValue || other.HasNoValue) | |
return false; | |
return _value.Equals(other._value); | |
} | |
public override int GetHashCode() | |
{ | |
return _value.GetHashCode(); | |
} | |
public override string ToString() | |
{ | |
if (HasNoValue) | |
return "No Value"; | |
return Value.ToString(); | |
} | |
public T Unwrap(T defaultValue = default(T)) | |
{ | |
if (HasValue) | |
return Value; | |
return defaultValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment