I have implemented an Option type for some project of mine like this:
public abstract Option<T> {}
public class None<T> : Option<T>
public class Some<T> : Option<T>
{
public T Value { get; }
public Some(T value)
{
Value = value;
}
}
For finding out if an Option contains a value I use this extension method which makes use of pattern matching:
public static bool TryGetValue<T>(this Option<T> option, out T value)
{
if (option is Some<T> some)
{
value = some.Value;
return true;
}
value = default;
return false;
}
I now get the following warning for return default;
Cannot convert null literal to non nullable reference or unconstrained type parameter
It is impossible for me to restrict the generic parameter T to class or struct.
For example, if I restricted the generic parameter to class, I couldn't generate Option<int?> instances as the Nullable<int> type is a struct itself. Declaring the out parameter as nullable via postfixing ? is also not a solution as it seems.
To me the type system is somewhat broken or not thoroughly thought through at this stage. Either Nullable should have been a class or there needs to be a generic parameter restriction like:
public static bool TryGetValue<T>(this Option<T> option, out T value)
where T : nullable [...]
Is there another approach that might be suitable for this issue? What am I missing?
Valueproperty on the abstract class, and in case ofNone<T>implement it by returning default, and onSome<T>by returning it's value? - EluciusFTW