9

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!

0

6 Answers 6

19

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.

4
  • I made a small mistake in my post - please see the updated like: EmployeeProfile prof = (EmployeeProfile)emp; // InvalidCastException here Dec 15, 2010 at 18:00
  • @WeekendWarrior: That doesn't matter. You still can't cast an instance of the base type to the derived type. You could cast in the other direction.
    – cdhowie
    Dec 15, 2010 at 18:01
  • What cdhowie says still stands, you are still trying to cast a basetype into a subtype.
    – DeusAduro
    Dec 15, 2010 at 18:01
  • Composition pattern makes sense. EmployeeProfile has a one-to-one relationship with an Employee - it just contains additional properties. thank you for the tip! Dec 15, 2010 at 18:15
18

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...

2
  • 1
    This is an excellent way of thinking about it... this helps a lot. thanks so much. Dec 15, 2010 at 18:07
  • if you had a list of Employee and Male and Female had unique properties, how would you count for example, how many Females have given birth? or how many Males have had a vasectomy? LoL trying to come up with examples following the classes mentioned. I need to know how to cast appropriately down to their type to get to the unique properties. THANKS!
    – Alex
    Jul 5, 2018 at 14:34
2

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;
2

You need to use a library like Automapper . This library can fill the matched properties for an object:

Mapper.Initialize(cfg => {
    cfg.CreateMap<EmployeeProfile,Employee>();
});

EmployeeProfile prof = Mapper.Map<EmployeeProfile>(emp);
0
0

You are going the wrong direction. In your code an EmployeeProfile is a special type of Employee, not the other way around. So when you try to cast in reverse, the compiler is saying that an 'Employee' is not derived from 'EmployeeProfile'

0

You'll need a method in EmployeeProfile taht takes an Employee as argument and creates an EmployeeProfile.

EmployeeProfile enrichEmployee(Employee emp)
{
   EmployeeProfile empprof = new EmployeeProfile();
   empprof.property1 = emp.property1;
   empprof.property2 = emp.property2;
   empprof.property3 = emp.property3;

   return empprof;
}
1
  • Is is not strictly true that you "need" a method in the derived class which assigns all properties from the base class. This is a long-winded way of performing the assignment of properties whereas an object-level assignment will work for all available, matching properties. Jan 9, 2019 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.