In a recent project, I had a need to upcast from a base class to a derived class. Below I describe the problem and the conditions where the upcast works. The same upcast will succeed if base class was cast initially from a derived class. for e.g., the following
C1 c1 = (c1) c2; // Downcast to base class
C2 c21 = (C2) c1; //The upcast will succeed
Consider that there is a method,
Method1, that returns an instance of class
C1.You don't have the ability to enhance
C1.
But, you would like to add new services to C1.
{
void NewFunctionality()
}
it would mean providing the new additional features that C2 may have.
will run successfully
C2 c2 = new C2();
Upcast base to derived class
So you derive C2 from C1
Class C2: C1
Now, examine the following code
C1 c1 = <SomeClass>.Method1();
// Now to use the NewFunctionalrity, have to upcast
C2 c2 = (C2) c1; //will not work !
Upcasting C1 to C2 will compile but fail at runtime causing an exception, CastException. There is no way for the compiler to do this upcast as
So why does it compile ?
Since "c1" was downcast from the derived type C2, the upcast succeeds.
0 comments
Hide comments