"Covariance" in System.Nullable <> struct
When we have two structures, and one is implicitly converted to the other, it looks like the versions of these two versions are also implicitly converted. For example, if struct A
has an implicit conversion to struct B
, then A?
also converted to B?
.
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 the method:
MyNumber? nmn = new MyNumber(42); int? covariantMagic = nmn; // works!
In C # Language Specification Version 4.0, we read that such a conversion must exist for "predefined implicit identification and numerical conversions".
But is it safe to assume that it will also work for custom implicit conversions?
(This question may be related to this error: http://connect.microsoft.com/VisualStudio/feedback/details/642227/ )
But is it possible to assume that it will also work for custom implicit conversions?
Yes. From section 6.4.2 of the C # 4 specification:
Given a custom conversion operator that translates from a value of type null-nullable
S
to a value type with a value of zero, does there exist an operator with a canceled conversion that converts fromS?
inT?
. This canceled conversion statement is deploying fromS?
toS
, followed by a custom conversion fromS
toT
, followed by a wrapper fromT
toT?
except that the zeroS?
is converted directly to the zero value ofT?
.The raised conversion operator has the same implicit or explicit classification as its base user-defined conversion operator. The term "custom conversion" applies to the use of both custom and canceled conversion operators.