Basically i want to do this. aa causes a bad cast exception.
NOTE: o can be ANYTHING. It may not be B, it can be C, D, E, F etc. But this should work as long as o is a class that can typecast into A (B is such a class. It uses an implicit operator overload)
var b = (B)"sz";
var a = (A)b;
object o = b;
var aa = (A)o;
Have you tried doing the following?
The reason this will work and your code doesn’t is that such explicit casts are statically compiled. In other words, when you say
(A)othe compiler looks for an explicit cast from object toAand doesn’t find one. However, it does determine thatAis a subclass of object, so the cast may be viable at runtime – and it inserts an attempt to runtime down-cast the instance into a field of typeA. Such runtime casts have nothing to do with explicit and/or implicit conversions; these simply follow the built-in type hierarchy rules.Another example: