Introduction
I am aware that \"user-defined conversions to or from a base class are not allowed\". MSDN gives, as an explanation to this rule, \"You
Well, when you are casting Entity to Body, you are not really casting one to another, but rather casting the IntPtr to a new entity.
Why not create an explicit conversion operator from IntPtr?
public class Entity {
public IntPtr Pointer;
public Entity(IntPtr pointer) {
this.Pointer = pointer;
}
}
public class Body : Entity {
Body(IntPtr pointer) : base(pointer) { }
public static explicit operator Body(IntPtr ptr) {
return new Body(ptr);
}
public static void Test() {
Entity e = new Entity(new IntPtr());
Body body = (Body)e.Pointer;
}
}