I have the following struct:
struct Generic<T>
{
public T Property { get; init; }
public Generic(T property) { Property = property; }
public static implicit operator T?(Generic<T> x)
=> x.GetHashCode() == 42 ? null : x.Property;
}
The compiler underlines the null in the implicit conversion and reports error CS0403:
Cannot convert
nullto type parameterTbecause it could be a non-nullable value type. Consider usingdefault(T)instead.
But I do not define a conversion to T, I define it to T?! Why does the compiler not see this? And what can I do to get rid of the compiler error?
Strangely, these two nongeneric versions - one with T being a struct, one with T being a class - do not give any compiler errors:
struct NongenericStruct
{
public int Property { get; init; }
public NongenericStruct(int property) { Property = property; }
public static implicit operator int?(NongenericStruct x)
=> x.GetHashCode() == 42 ? null : x.Property;
}
struct NongenericClass
{
public string Property { get; init; }
public NongenericClass(string property) { Property = property; }
public static implicit operator string?(NongenericClass x)
=> x.GetHashCode() == 42 ? null : x.Property;
}