Playing with the new nullable reference types in C#. Glad to see they poached this from Swift! It's such a great feature! BUT... since it's essentially 'bolted-on' to the language, I'm struggling to create a generic that can take any nullable type whether value or reference, which is trivial in Swift.
Consider this class:
public abstract class LabeledValue<TValue> {
public string label { get; set; }
public TValue? value { get; set; }
}
Here's what I'm trying to achieve, using the types Int
(value-type) and Foo
(reference type) as examples:
public class LabeledInt : LabeledValue<Int>{}
var myLabeledIntA = new LabeledInt(){
label = "Int is set",
value = 44
}
var myLabeledIntB = new LabeledInt(){
label = "Int is not set",
value = null
}
public class LabeledFoo : LabeledValue<Foo>{}
var myLabeledFooA = new LabeledFoo(){
label = "Foo is set",
value = new Foo()
}
var myLabeledFooB = new LabeledFoo(){
label = "Foo is not set",
value = null
}
This complains that I have to define TValue as nullable. However I can't find a constraint that solves both nullable value types (i.e. Int?) and nullable reference types (i.e. Foo?). How would one write such a constraint?
These don't work...
public abstract class LabeledValue<TValue>
where TValue : Nullable {
public string label { get; set; }
public TValue? value { get; set; }
}
public abstract class LabeledValue<TValue>
where TValue : struct {
public string label { get; set; }
public TValue? value { get; set; }
}
public abstract class LabeledValue<TValue> {
public string label { get; set; }
public Nullable<TValue> value { get; set; }
}
Note, I also tried this thinking the nullability could just be passed in as the actual type parameter, but then it complains that 'value' isn't set.
public abstract class LabeledValue<TValue> {
public string label { get; set; }
public TValue value { get; set; }
}
public class LabeledInt : LabeledValue<Int?>{}