If I have this code, it will compile and work as it should:
class MyNumber // Just a class. { static public explicit operator MyNumber(byte b) { return new MyNumber(); } } Decimal d = new Decimal(); MyNumber c1 = (MyNumber)d;
The perfection of some people is a bit surprising, as there is no explicit expression from decimal to MyNumber . But since there is an explicit order from decimal to byte , as well as an explicit selection from byte to MyNumber , the compiler is kind enough to insert an extra explicit cast into it.
In short: if a programmer uses an explicit cast, the compiler takes the liberty of looking for another explicit cast so that this all happens.
So ... I tried the same with my own classes. Instead of byte and decimal I used MyByte and Mydecimal . The code is as follows:
class MyDecimal // Simulates a decimal. { static public explicit operator MyByte(MyDecimal a)
The last line will not compile. It gives an error: "It is not possible to convert the type" DoubleExplicitCasts.Program.MyDecimal "to" DoubleExplicitCasts.Program.MyNumber "". Well ... why not ???
So my question is: Why do explicit operators inside a .NET system receive special treatment, and my explicit user statements do not work?
EDIT
I know that this code does not work and the values ββare not passed from one instance to another, but this does not apply to the point.
source share