Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

downcast

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

  }           

}
like image 939
Israel Lot Avatar asked Apr 16 '12 10:04

Israel Lot


1 Answers

Create an interface. And since you can't modify Employee, create an adapter that you own:

class EmployeeAdapter : IEmployee
{
    private Employee emp;
    public EmployeeAdapter(Employee emp) { this.emp = emp; }
    public int SomeMethodInEmployee() { return emp.SomeMethodInEmployee(); }
}

class AdvancedEmployee : IEmployee { } 
like image 83
Torbjörn Kalin Avatar answered Nov 03 '22 15:11

Torbjörn Kalin