j_lainio
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?
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) { }
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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");
// 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");
You can type cast them both employee and manager to iemployee , though.