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

j_lainioAsked:
Who is Participating?
 
philipjonathanConnect With a Mentor Commented:
You cannot cast a superclass into its subclass, unless the actuall object type is the subclass.

However, most of the time what you need is to cast the subclass into its superclass:
Employee emp = new Manager("Johnson");

This way you can treat all employee as a whole.
Let's say you want to increase salary, then:
foreach (Employee emp in employees)
  emp.IncreaseSalary();

Only if you really know that the actual object is the subclass, then you can cast to the subclass:
foreach (Employee emp in employees)
{
  if (emp is Manager)
  {
    Manager mgr = (Manager) emp; // this will not generate exception
    mgr.GiveBiggerCubicle();
  }
}

If you tell us what you really need, probably we can help you better
0
 
quincydudeCommented:
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.
0
 
Anurag ThakurTechnical ManagerCommented:
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");
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.