Upcast base to derived class

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.Consider that there is a method,

ITPro Today

January 27, 2005

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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.

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.  So you derive C2 from C1

Class C2: C1
{
    void NewFunctionality()
}

Now, examine the following code

C1 c1 = .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
it would mean providing the new additional features that C2 may have.

 

So why does it compile ?

 

The same upcast will succeed if base class was cast initially from a derived class. for e.g., the following
will run successfully
 
   C2 c2 = new C2();

  C1 c1 = (c1) c2;   // Downcast to base class

   C2 c21 = (C2) c1;   //The upcast will succeed

Since "c1" was downcast from the derived type C2, the upcast succeeds.

 

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like