When I compile the following code, I only see the error during Run-time which says
“Unable to cast object of type ‘Foo1’ to type ‘Foo2′”
Why is the compiler not showing this error during compile time?
public void Start()
{
Foo1 objFoo1 = new Foo1();
Foo2 objFoo2 = (Foo2)objFoo1;
//objFoo1.FooA = 10;
//Console.WriteLine(objFoo2.FooA);
}
public class Foo1 {}
public class Foo2 : Foo1 {}
The compiler is not smart enough to know that
objFoo1is really a simpleFoo1. It doesn’t analyze your source code deeply enough to determine that. All it sees is thatobjFoo1is aFoo1,Foo2is derived fromFoo1, and therefore the cast is legal. If instead you changed that to(int) objFoo1it would bomb at compile-time since the compiler could see that there’s no possible way to turn aFoo1into an integer.Imagine that there were 1000 lines of code between the two declarations, many of them doing various assignments to
objFoo1. The compiler would have to do a lot of hard work to attempt to determine what object exactly is inobjFoo1. In general it wouldn’t always be able to do so. It’s far easier for the compiler to just take the static type information at face value and assume thatobjFoo1is some type ofFoo1object but no more. That way it doesn’t reject your simple test program but accept a more complicated one.It’s also not the compiler’s job to reject your code, in this case. It is possible, though admittedly far-fetched, that you are intentionally trying to generate a
ClassCastExceptionby doing an illegal cast. It’d be unusual but not illegal to do that.Along these lines, there are other cases where the compiler’s static code analysis can be fooled. This will fail to compile:
While this will compile fine even though it is semantically identical: