Wednesday, June 5, 2013

Runtime Polymorphism

In C# Dynamic Polymorphism or Runtime Polymorphism is achieved using the concept of inheritance; the methods defined in the base class can be overridden in the derived class and can be called dynamically at runtime.

The following example explains Dynamic or Runtime Polymorphism.

We have a base class DynamicPolymorphism, and 2 derived classes Child1 & Child2. There is a handler class DynamicPolymorphismHandler which takes a parameter of the base class type and calls the Print method which is declared in the base class and overridden in the derived classes.
    class DynamicPolymorphism
    {
        public virtual void Print()
        {
            Console.WriteLine("Printing from Base Class.");
        }      
    }
    //
    class Child1 : DynamicPolymorphism
    {
        public override void Print()
        {
            Console.WriteLine("Printing from Child1 Class.");
        }
    }
    //
    class Child2 : DynamicPolymorphism
    {
        public override void Print()
        {
            Console.WriteLine("Printing from Child2 Class.");
        }
    }
    //
    class DynamicPolymorphismHandler
    {
        public void CallFunction(DynamicPolymorphism objHandle)
        {
            objHandle.Print();
        }
    }

Now let us see on how to use dynamic Polymorphism to call the methods of the derived classes using the base class object.

    DynamicPolymorphismHandler objDynamicPolymorphismHandler = new DynamicPolymorphismHandler();
    Child1 objChild1 = new Child1();
    Child2 objChild2 = new Child2();
    //
    objDynamicPolymorphismHandler.CallFunction(objChild1);
    objDynamicPolymorphismHandler.CallFunction(objChild2);

We create instances of the derived classes and pass them to the Handler class, but notice that the handler class takes a parameter of the base class type. Here we can decide at runtime on what object to be passed to the handler class. The code will execute and print the following output.

Printing from Child1 Class.
Printing from Child2 Class.


Search Flipkart Products:
Flipkart.com

No comments: