c# - Multiple system explicit converters are allowed, but mutiple user explicit converters are not. Why? -


if have code, compile , work should:

class mynumber // class. {     static public explicit operator mynumber(byte b)     {         return new mynumber();     } }  decimal d = new decimal(); mynumber c1 = (mynumber)d; 

perhapse people bit of surprise, since there no existing explicit cast decimal mynumber. since there explicit cast decimal byte , there explicit cast byte mynumber, compiler kind enough insert explicit cast me.

in short: if programmer uses explicit cast, compiler takes freedom search other explicit cast whole thing going.

so... tried same thing own classes. instead of byte , decimal, used mybyte , mydecimal. code looks this:

class mydecimal // simulates decimal. {     static public explicit operator mybyte(mydecimal a) // in decimal.     {         return new mybyte();     } }  class mybyte // simulates byte. { }  class mynumber // class. {     static public explicit operator mynumber(mybyte b)     {         return new mynumber();     } }  mydecimal d = new mydecimal(); mynumber c2 = (mynumber)d; // <== not compile! 

the last line not compile. gives error: "cannot convert type 'doubleexplicitcasts.program.mydecimal' 'doubleexplicitcasts.program.mynumber'". well... why not???

so question is: why explicit operators inside .net system special treatment , user explicit operators not?

edit
know code not functional , values not transfered 1 instance another, beside point.

imo, lead "happy debugging" , really, complicated , non-obvious code.

just imagine 3 or more levels of such user-defined conversions, , how search error, caused conversion in middle (e.g such conversion introduced mistake or not supposed used in situation).

thanks god such behaviour not supported.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -