3 using System.Diagnostics.CodeAnalysis;
7 public readonly
struct Option<T> where T : notnull
9 private readonly
bool hasValue;
10 private readonly T? value;
12 private Option(
bool hasValue, T? value)
14 this.hasValue = hasValue;
21 public bool TryUnwrap<T1>([NotNullWhen(returnValue:
true)] out T1? outValue) where T1 : T
23 bool hasValueOfGivenType =
false;
26 if (hasValue && value is T1 t1)
28 hasValueOfGivenType =
true;
32 return hasValueOfGivenType;
35 public bool TryUnwrap([NotNullWhen(returnValue:
true)] out T? outValue)
36 => TryUnwrap<T>(out outValue);
44 public T
Match(Func<T, T> some, Func<T> none)
45 =>
TryUnwrap(out T? selfValue) ? some(selfValue) : none();
47 public void Match(Action<T> some, Action none)
61 =>
IsSome() ? this : fallback;
66 var t when t == typeof(
bool)
67 =>
throw new Exception(
"Option type rejects booleans"),
68 {IsConstructedGenericType:
true} t when t.GetGenericTypeDefinition() == typeof(
Option<>)
69 =>
throw new Exception(
"Option type rejects nested Option"),
70 {IsConstructedGenericType:
true} t when t.GetGenericTypeDefinition() == typeof(Nullable<>)
71 =>
throw new Exception(
"Option type rejects Nullable"),
73 =>
new Option<T>(hasValue:
true, value: value ??
throw new Exception(
"Option type rejects null"))
76 public override bool Equals(
object? obj)
90 =>
TryUnwrap(out T? selfValue) && selfValue.Equals(otherValue);
93 =>
TryUnwrap(out T? selfValue) ? selfValue.GetHashCode() : 0;
109 ? $
"Some<{typeof(T).Name}>({selfValue})"
110 : $
"None<{typeof(T).Name}>";
113 public static class Option
Option< T > Fallback(Option< T > fallback)
void Match(Action< T > some, Action none)
override bool Equals(object? obj)
bool ValueEquals(T otherValue)
T Match(Func< T, T > some, Func< T > none)
override string ToString()
bool TryUnwrap< T1 >([NotNullWhen(returnValue:true)] out T1? outValue)
bool TryUnwrap([NotNullWhen(returnValue:true)] out T? outValue)
static Option< T > Some< T >(T value)
static bool operator!=(Option< T > a, Option< T > b)
static Option< T > None()
static Option< T > Some(T value)
override int GetHashCode()
static bool operator==(Option< T > a, Option< T > b)
static UnspecifiedNone None
Option< TType > Bind< TType >(Func< T, Option< TType >> binder)
Option< TType > Select< TType >(Func< T, TType > selector)