views:

76

answers:

1

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;
+4  A: 

Have you tried doing the following?

[...]
var ee = (A)(B)o;

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)o the compiler looks for an explicit cast from object to A and doesn't find one. However, it does determine that A is 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 type A. Such runtime casts have nothing to do with explicit and/or implicit conversions; these simply follow the built-in type hierarchy rules.

Another example:

object o = 1.0;
int i = (int)o; //throws InvalidCastException - even though (int)1.0 is OK.
Eamon Nerbonne
edit to make this more clear.
acidzombie24
+1 for explaining why operator overloads wont work. I'm likely to accept this.
acidzombie24
Right. It is exactly the same as overload resolution. If you say "ob = giraffe" and you have overloaded methods M(object) and M(Animal) then M(ob) chooses the object overload at compile time no matter what ob is at runtime. The compiler chooses the "object to A" conversion operator over the "B to A" conversion operator because that's what's known at compile time. That's what you get for having a statically typed language; if you want it to be dynamically typed, then (1) use a dynamically typed language, or (2) use the dynamic keyword in C# 4.
Eric Lippert