• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 412
  • Last Modified:

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

0
j_lainio
Asked:
j_lainio
1 Solution
 
philipjonathanCommented:
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 ThakurCommented:
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now