Speeding up (using (Employee)someInstance ) is usually easy, as the compiler can tell you at compile time if the type is derived from another.
Downcasting , however, should be performed at runtime, as a rule, since the compiler may not always know if a given instance is of the specified type. C # provides two operators for this - - , which tells you whether downcast is working and returns true / false. And like , that tries to perform a cast and returns the correct type if possible, or null if not.
To check 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 Oct 06 '09 at 8:10 2009-10-06 08:10
source share