If I have this code, this 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;
Perhapse some people are a bit of a surprise, since there is no existing explicit cast from a decimal
to MyNumber
. But since there is a explicit cast from decimal
to byte
and there is also a explicit cast from a byte
to MyNumber
, the compiler is kind enough to insert that extra explicit cast for me.
In short: If the programmer uses an explicit cast, the compiler takes the freedom to search for other explicit cast to get the whole thing going.
So... I tried the same thing with my own classes. Instead of byte
and decimal
, I used MyByte
and Mydecimal
. The code looks like this:
class MyDecimal // Simulates a decimal.
{
static public explicit operator MyByte(MyDecimal a) // Just like in a decimal.
{
return new MyByte();
}
}
class MyByte // Simulates a byte.
{
}
class MyNumber // Just a class.
{
static public explicit operator MyNumber(MyByte b)
{
return new MyNumber();
}
}
MyDecimal d = new MyDecimal();
MyNumber c2 = (MyNumber)d; // <== Will not compile!
The last line will not compile. It gives the error: "Cannot convert type 'DoubleExplicitCasts.Program.MyDecimal' to 'DoubleExplicitCasts.Program.MyNumber'". Well... why not???
So my question is: Why do the explicit operators inside .NET system get a special treatment and my user explicit operators do not?
EDIT
I know this code is not functional and values are not transfered from one instance to another, but that is beside the point.