I get the following exception:
InvalidCastException: Unable to cast object of type 'Employee' to type 'EmployeeProfile'.
I have the following code:
private class Employee
{
public string Name { get; private set; }
public Employee()
{
this.Name = "employee";
}
public override string ToString()
{
return this.Name;
}
}
private class EmployeeProfile : Employee
{
public string Profile { get; private set; }
public EmployeeProfile() : base()
{
this.Profile = string.Format("{0}'s profile", this.Name);
}
public override string ToString()
{
return this.Profile;
}
}
public void RunTest()
{
Employee emp = new Employee();
EmployeeProfile prof = (EmployeeProfile)emp; // InvalidCastException here
System.Console.WriteLine(emp);
System.Console.WriteLine(prof);
}
Maybe my brain is burned out, but I thought you can cast a subtype to its base type? What am I missing here? Maybe it is a vacation... thank you!
You can cast a subtype to its base type. But you are casting an instance of the base type to the subtype.
An EmployeeProfile is-an Employee. Not necessarily the other way around.
So this would work:
EmployeeProfile prof = new EmployeeProfile();
Employee emp = prof;
However, this model reeks of bad design. An employee profile is not a special kind of an employee, is it? It makes more sense for an employee to have a profile. You are after the composition pattern here.
All the answers are correct...just providing a no frills simple explanation...
class Employee
class Female : Employee
class Male: Employee
Just because you are an Employee
does not make you a Female
...
Maybe my brain is burned out, but I thought you can cast a subtype to its base type?
You are attempting to cast a basetype to its subtype. Exactly the opposite of what you say:
Employee emp = new Employee();
EmployeeProfile prof = emp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With