简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM