struct When we have two structures, and one is implicitly converted to the other, it looks like the versions of ...">

"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/ )

+6
source share
1 answer

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 from S? in T? . This canceled conversion statement is deploying from S? to S , followed by a custom conversion from S to T , followed by a wrapper from T to T? except that the zero S? is converted directly to the zero value of T? .

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.

+6
source

Source: https://habr.com/ru/post/915290/


All Articles