Alex Rivera | Logout

Cast base instance to derived class (downcast) in C#

Asked 2012-04-16T10:53:50.203
9

Suppose I have two classes:

class Employee 

and

class AdvancedEmployee:Employee

I know something like this won't work, as I can't downcast on C#:

var employee = new Employee();
var advanced = employee as AdvancedEmployee;

My question is: How to accomplish downcast in a efficient way? Actually I have a constructor on AdvancedEmployee that takes a Employee as parameter and use it to inject its values, basically making a clone.


Update

To solve the data that would get duplicated I changed the approach a bit and now AdvancedEmployee CONTAINS an employee rather than being one itself. Example:

class Employee;

class AdvancedEmployee
{
   private employee

   public AdvancedEmployee(Employee employee){

    this.employee = employee

  }           

}
Edit
Report

2 Answers

6

It can not be a cast, it's actually a conversion between different types.

I would add a ctor or static member function like AdvancedEmployee FromBase(Employee e), to construct derived type from given base type.

answered 2012-04-16T10:57:43.600
2

Creating a new object is the most readable and clearest way. You can also define explicit or implicit type-conversion operators in your Employee class.

public static explicit operator AdvancedEmployee(Employee e)
{
    return new AdvancedEmployee(e);
}

And then use it like this:

var e = new Employee();
var ae = (AdvancedEmployee) e;
answered 2012-04-16T10:59:16.897

Your Answer