Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Inheritance & Casting

Tags:

c#

inheritance

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!

like image 996
Steven Striga Avatar asked Dec 15 '10 17:12

Steven Striga


3 Answers

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.

like image 112
cdhowie Avatar answered Sep 28 '22 02:09

cdhowie


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

like image 21
Aaron McIver Avatar answered Sep 28 '22 01:09

Aaron McIver


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;
like image 36
DeusAduro Avatar answered Sep 28 '22 02:09

DeusAduro