CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
// Use "as" to test compatability.
Hexagon hex2 = frank as Hexagon;
if (hex2 == null)
Console.WriteLine("Sorry, frank is not a Hexagon...");
The C# is Keyword
Given that the GivePromotion() method has been designed to take any possible type derived from
Employee, one question on your mind may be how this method can determine which derived type was
sent into the method. On a related note, given that the incoming parameter is of type Employee, how can
you gain access to the specialized members of the SalesPerson a nd Manager types?
In addition to the as keyword, the C# language provides the is keyword to determine whether two
items are compatible. Unlike the as keyword, however, the is keyword returns false, rather than a null
reference, if the types are incompatible. Consider the following implementation of the GivePromotion()
method:
static void GivePromotion(Employee emp)
{
Console.WriteLine("{0} was promoted!", emp.Name);
if (emp is SalesPerson)
{
Console.WriteLine("{0} made {1} sale(s)!", emp.Name,
((SalesPerson)emp).SalesNumber);
Console.WriteLine();
}
if (emp is Manager)
{
Console.WriteLine("{0} had {1} stock options...", emp.Name,
((Manager)emp).StockOptions);
Console.WriteLine();
}
}
Here, you are performing a runtime check to determine what the incoming base class reference is
actually pointing to in memory. After you determine whether you received a SalesPerson or Manager
type, you are able to perform an explicit cast to gain access to the specialized members of the class. Also
notice that you are not required to wrap your casting operations within a try/catch construct, as you
know that the cast is safe if you enter either if scope, given your conditional check.
The Master Parent Class: System.Object
To wrap up this chapter, I’d like to examine the details of the master parent class in the .NET platform:
Object. As you were reading the previous section, you might have noticed that the base classes in your
hierarchies (Car, Shape, Employee) never explicitly specify their parent classes:
// Who is the parent of Car?
class Car
{...}
243