Introduction
I know that "custom conversions to or from the base class are not allowed." MSDN gives "This operator is not needed" as an explanation for this rule.
I understand that a custom conversion to the base class is not required, as this is explicitly done implicitly. However, I need a conversion from the base class.
In my current project, an unmanaged code wrapper, I use a pointer stored in the Entity class. All classes that use a pointer get this Entity class, for example, the Body class.
Therefore I:
Method a
class Entity { IntPtr Pointer; Entity(IntPtr pointer) { this.Pointer = pointer; } } class Body : Entity { Body(IntPtr pointer) : base(pointer) { } explicit operator Body(Entity e) { return new Body(e.Pointer); } }
This spell is illegal. (Please note that I did not write accessories). Without it, the compiler will allow me to do:
Method B
(Body)myEntity ...
However, at runtime, I get an exception saying that this cast is not possible.
Conclusion
So here I need a custom conversion from a base class, and C # fails me. Using method A, the compiler will complain, but the code will logically work at runtime. Using method B, the compiler will not complain, but the code obviously will not work at runtime.
In this situation, it seems strange to me that MSDN tells me that I do not need this operator, and the compiler acts as if it were possible implicitly (method B). What should I do?
I know I can use:
Solution A
class Body : Entity { Body(IntPtr pointer) : base(pointer) { } static Body FromEntity(Entity e) { return new Body(e.Pointer); } }
Solution B
class Body : Entity { Body(IntPtr pointer) : base(pointer) { } Body(Entity e) : base(e.Pointer) { } }
Solution C
class Entity { IntPtr Pointer; Entity(IntPtr pointer) { this.Pointer = pointer; } Body ToBody() { return new Body(this.Pointer); } }
But honestly, all the syntax for them is terrible and in fact should be great. So, any way to make the throws work? Is this a flaw in C # design or am I missing an opportunity? It is as if C # did not trust me enough to write my own transformation from basic to child using my casting system.