C# Classes Theory Part 4 Polymorphism


Polymorphism

One consequence of inheritance is that classes deriving from a base class have an overlap in the methods and properties that they expose. Because of this, it is often possible to treat objects instantiated from classes with a base type in common using identical syntax. For example, if a base class called Animal has a method called EatFood(), then the syntax for calling this method from the derived classes Cow and Chicken will be similar:

Cow myCow = new Cow();
Chicken myChicken = new Chicken();
myCow.EatFood();
myChicken.EatFood();

Polymorphism takes this a step further. You can assign a variable that is of a derived type to a variable of one the base types, as shown here:

Animal myAnimal = myCow;

No casting is required for this. You can then call methods of the base class through this variable:

myAnimal.EatFood();

This results in the implementation of EatFood() in the derived class being called.

Note that you can’t call methods defined on the derived class in the same way. The following code won’t work:
myAnimal.Moo();
However, you can cast a base type variable into a derived class variable and call the method of the derived class that way:

Cow myNewCow = (Cow)myAnimal;
myNewCow.Moo();

“This casting causes an exception to be raised if the type of the original variable was anything other than Cow or a class derived from Cow.” This is what the book I am reading says.

Remember that in C# all classes derive from the base class object at the root of their inheritance hierarchies. It is therefore possible to treat all objects as instances of the class object.

Leave a comment

Your email address will not be published. Required fields are marked *