4 ms·
Something which I've used in the past (edited because I spotted some mistakes while re-reading the code [grin]): public readonly struct Option<T> {
by mdpopescu 6y ago
Something which I've used in the past (edited because I spotted some mistakes while re-reading the code [grin]):
public readonly struct Option<T>
{
public static readonly Option<T> NONE = new Option<T>();
//
public T Value { get; }
public bool HasValue { get; }
public Option(T value)
{
Value = value;
HasValue = value is { };
}
public Option<TR> Select<TR>(Func<T, TR> selector) => HasValue ? new Option<TR>(selector(Value)) : Option<TR>.NONE;
public Option<TR> SelectMany<TR>(Func<T, Option<TR>> selector) => HasValue ? selector(Value) : Option<TR>.NONE;
public T OrElse(T defValue = default) => HasValue ? Value : defValue;
}
You can of course add more utility functions besides these, eventually as extension methods, but it's a starting point.
- ryanjshaw 6y agoYou can also use a library like LanguageExt. In practice I'm torn between how neat and logical it looks, and wasting 30min figuring out I used the wrong match() on a mixed sync/async scenario after a method signature changed and that's why my database context is disposed of randomly in the middle of operations.