user160677
user160677

Reputation: 4303

Why do I need an explicit downcast if my object of type "object" is pointing to the correct instance in hierarchy?

Consider the following inheritance:

abstract class Employee
{
     private string empID;
     private string empName;
}   

class SoftwareDeveloper : Employee 
{
    ............    
}

class MarketingPerson : Employee
{
    ........... 
}

static void Main()
{
    Employee Jaffer = new SoftwareDeveloper();
    Employee George = new MarketingPerson();

    // Ok because of is-a relationship    
    LayOff(Jaffer);

    // Ok because of is-a relationship    
    LayOff(George);

    object Leo = new MarketingPerson();

    // Error because downcast is required as (MarketingPerson) Leo
    LayOff(Leo);
}

static bool LayOff(Employee emp)
{
    // some Business Logic
    return true;
}

Even though the declaration object Leo = new MarketingPerson() points to an instance of MarketingPerson, why do I need to downcast?

Upvotes: 1

Views: 231

Answers (3)

MemoryLeak
MemoryLeak

Reputation: 7318

The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. For more information, see Boxing and Unboxing.

Upvotes: 0

Orion Edwards
Orion Edwards

Reputation: 123642

You need to cast because the compiler only knows the declared types.

In your example, object Leo = new MarketingPerson();, you are declaring that the variable Leo is of type object. You can put a MarketingPerson (or anything else) in that variable, but it's still declared as an object.

The LayOff method is declared as accepting an Employee - as object does not derive from employee, you need to cast it to tell the compiler "I am forcing this object into an Employee

Upvotes: 8

Thomas Levesque
Thomas Levesque

Reputation: 292405

Because an object is not an Employee. The compiler doesn't know that Leo is set to an instance of Employee, it only knows that it is an object

Upvotes: 2

Related Questions