Beginners C# Tutorial - Polymorphism

Beginners C# Tutorial - PolymorphismPolymorphism. It allows you to implement derived class methods through a base class pointer during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won’t necessarily have to be the same object type. However, if they’re related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this.


After the array is initialized, there is a foreach loop that looks at each element of the array. Within the foreach loop the Draw() method is invoked on each element of the dObj array. Because of polymorphism, the run-time type of each object is invoked. The type of the reference object from the dObj array is a DrawingObject. However, that doesn’t matter because the derived classes override the virtual Draw() method of the DrawingObject class. This makes the overriden Draw() methods of the derived classes execute when the Draw() method is called using the DrawingObject base class reference from the dObj array. Here’s what the output looks like:

Website: www.freewebs.com | Filesize: 75kb
No of Page(s): 4
Click here to download Beginners C# Tutorial - Polymorphism.

Related Tutorial

Tags: , ,

Comments

Leave a Reply