Thursday, November 6, 2014

Downcast from Base Type to Derived Type in C#

There are times when developers try to Downcast an object of a Base Type to Derived Type.
Well !! in the nutshell it is not allowed by design.

We will see why with a trivial example
Lets have Employee class  as a base class and Manager class  a  derived class from the Employee

class Employee
    {

    }
class Manager : Employee
    {

    }
class Program
    {
        static void Main(string[] args)
        {
          //This is definitely not allowed
          //(Compile time casting exception)            
             Manager Mngr= new Employee();   

          // Well this seems to be ok(No compile time error) 
            Manager Mngr= (Manager)new Employee();
         }
    }

Run the above code
Result:Unable to cast object of type 'Employee' to type 'Manager'


Can every Employee be a Manager??
That is definitely not true.so the behavior looks correct.

Now lets see in which situation the downcast is successful.

For the cast to be successful, the instance you are down casting must be a instance of the class that you are down casting to.

Not clear enough !! .

Let me use the same example to clear the above statement.

static void Main(string[] args)
        {
            //Will say Manager is an employee. Well he is 
             Employee Emp = new Manager();

            // Now cast the Emp back to Manager
              Manager Mngr = (Manager)Emp;

         }

Run the  code with the above changes .
Result: the cast works..

We would want to void  the above scenario with a better design  using Interface (will talk more on interface in  another post) .

There is a tricky work around that would work for some scenarios
That is Serialize the base class type and then Deserialize it to the derived class type,
but this approach is only good if you have simple class structure and not too many objects to process

 static void Main(string[] args)
   {
     Employee Emp = new Employee();
     var IntermediateObject = JsonConvert.SerializeObject(Emp);
     Manager Mngr = JsonConvert.DeserializeObject(IntermediateObject);
   }

*using Newtonsoft.Json to Serialize and Deserialize


  

1 comment: