Link to home
Start Free TrialLog in
Avatar of j_lainio
j_lainioFlag for Finland

asked on

How to convert object from class B to class A?

I get InvalidCastException when trying to convert Employee object to Manager object? See attached code snippet.

How should I write Employee and Manger classes, so they are convertible to both directions?


class Program
{
    static void Main(string[] args)
    {
        // This gives you InvalidCastException...
        Manager mgr = (Manager)new Employee("Johnsson");
        Console.ReadLine();
    }
}
 
public interface IEmployee
{
    string Name { get; set; }
}
 
public class Employee : IEmployee
{
    public string Name { get; set; }
    public Employee(string name)
    {
        Name = name;
    }
}
 
public class Manager : Employee
{
    public Manager(string name) : base(name) { }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of philipjonathan
philipjonathan
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think it's not really possible as you inherit Manager from  Employee and Employee from IEmployee. So in other words, Manager is a kind of employee and employee is a kind of IEmployee. But you cannot say employee is a kind of manager.

You can type cast them both employee and manager to iemployee , though.
you cannot get the Manager object by calling the Employee constructor and its correct you will get the invalid cast exception

// This gives you InvalidCastException...
Manager mgr = (Manager)new Employee("Johnsson");
Console.ReadLine();

this is correct
Manager mgr = new Manager("Johnsson");

or
Employee mgr = new Manager("Johnsson");