tags:

views:

661

answers:

2

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 emp 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 Managers, how can i downcast them where possible?

+5  A: 

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 (manager != null)
{
    //do something with it
}

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

RCIX
I need example to know what is Downcasting ?
Avoid redefining well-established terms: “boxing”, in the context of OOP and C#, means something rather different (= wrapping a value type object into a reference). Also, your example could (and should) use the `as` operator instead of `is`, followed by a cast.
Konrad Rudolph
I stand corrected on the first point, and i changed the second half of my answer to show both ways of doing it.
RCIX
Thank you very much things are cleared.Thanks to all.
You're very welcome. If you feel that this is the best answer, would you mind checking off the little checkmark to the left of this answer?
RCIX
I already checked ! Have a great day . :)
Thanks a bunch, you too :)
RCIX
+6  A: 

Upcasting (using (Employee)someInstance) is generally easy as the compiler can tell you at compile time if a type is derived from another.

Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.

To test if an employee is a manager:

Employee m = new Manager();
Employee e = new Employee();

if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");

You can also use this

Employee someEmployee = e  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (e) is a manager");

Employee someEmployee = m  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (m) is a manager");
Preet Sangha
Thank you very much Preet Sangha.