Why can't I use an interface with an explicit statement?

I'm just wondering if anyone knows why you are not allowed to use interfaces with implicit or explicit operators?

eg. this leads to a compile-time error:

public static explicit operator MyPlayer(IPlayer player) { ... } 

"custom conversions to or from the interface are not allowed"

Thank,

+22
explicit c # type-conversion
Mar 12 '10 at 14:05
source share
1 answer

Section 10.9.3 of the C # specification talks about this. The short version is that it is forbidden, so that the user can be sure that conversions between reference types and interfaces will be successful if and only if the reference type actually implements this interface and that the fact that the same object is actually referenced.

Defining an implicit or explicit conversion between reference types gives the user the expected change in the link; after all, the same link cannot be of two types. On the other hand, the user has no expectations for conversions between reference types and interface types.

User-defined conversions are not allowed for conversion from or to interface types. In particular, this limitation guarantees the absence of user conversions when converting to an interface type and that the conversion to an interface type is successful only if the converted object actually implements the specified interface type.

+29
Mar 12 '10 at 14:09
source share



All Articles