user184805 user184805 - 1 month ago 5
C# Question

downcast and upcast

I am new to C# (and OOP). When I have some code like the following:

class Employee
{
// some code
}


class Manager : Employee
{
//some code
}


Question 1: If I have other code that does this:

Manager mgr = new Manager();
Employee emp = (Employee)mgr;


Here
Employee
is a
Manager
, but when I cast it like that to an
Employee
it means I am upcasting it?

Question 2:

When I have several
Employee
class objects and some but not all of them are
Manager
's, how can I downcast them where possible?

Answer
  1. That is correct. When you do that you are casting it it into an "employee" object, so that means you cannot access anything manager specific.

  2. Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:

    if (employee is Manager)
    {
        Manager m = (Manager)employee;
        //do something with it
    }
    

or with the as operator like this:

Manager m = (employee as Manager);
if (m != null)
{
    //do something with it
}

If anything is unclear I'll be happy to correct it!