I'm using C# 9 and I ran into this odd problem, so I wrote a simple example below that demonstrates it. I need to set the value of a nullable enum to null, but I get an error when doing it through a generic type. If I hard-code the enum type into the class it works fine, so I'm not sure why it doesn't work when the same type is used as a generic. It seems like TOption?
is treated as TOption
with the nullable part ignored, which would make this error make sense as it would be trying to assign null to a non-nullable value type.
Is this a strange conflict between nullable types, value types, and compiler assumptions? Shouldn't TOption?
be treated exactly the same as Option?
when Option
is used as the generic type?
Note that I cannot constraint TOption
to be a value type in my actual case which fixes this problem, and I don't think this constraint should be necessary. I don't need TOption
to be a value type, I just need that field to be nullable -- regardless if it's a class or struct.
In regards to putting Option?
in for TOption
, I still need fields that treat it as non-nullable. So I cannot do this, I need the actual type in the generic but I need to be able to distinguish non-nullable and nullable fields of that type -- independent of the type being a struct or class. I should point out that I am using nullable reference types, so classes are treated as non-nullable unless specified with ?
.
public class Program
{
public static void Main(string[] args)
{
var test = new Test<Option>();
test.Option1 = null;
test.Option2 = null; // Cannot convert null to 'Program.Option' because it is a non-nullable value type
}
public enum Option { A, B, C }
public class Test<TOption>
{
public Option Option0 { get; set; }
public Option? Option1 { get; set; }
public TOption? Option2 { get; set; }
}
}