When we have two structs, and one is implicitly convertible to the other, then it seems like the System.Nullable<> versions of the two are also implicitly convertible. Like, if struct A has an implicit conversion to struct B, then A? converts to B? as well.
Here is an example:
struct MyNumber
{
public readonly int Inner;
public MyNumber(int i)
{
Inner = i;
}
public static implicit operator int(MyNumber n)
{
return n.Inner;
}
}
Inside some method:
MyNumber? nmn = new MyNumber(42);
int? covariantMagic = nmn; // works!
In the C# Language Specification Version 4.0 we read that a conversion like this shall exist for “the predefined implicit identity and numeric conversions”.
But is it safe to assume that it will also work for user-defined implicit conversions?
(This question might be related to this bug: http://connect.microsoft.com/VisualStudio/feedback/details/642227/)
Yes. From section 6.4.2 of the C# 4 spec: