Runtime polymorphism in c#


What is runtime polymorphism?

By runtime polymorphism we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding .In Object oriented languages like Visual C++ we can use pointers to achieve runtime polymorphism C# is also object oriented programming language that facilitates the same functionality of runtime polymorphism as VC++ does.

Implementation:

In this article I will write the code first about the classes and explain you later how its achieved in c#.

class Shape
    {
        public virtual void Draw()
        {

        }
    }

    class Ractangel:Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Rectangle Drawn ");
        }
 
    }

     class Circle:Shape
    {
        public override void  Draw()
        {
            Console.WriteLine("Circle Drawn ");
           
        }

    }
     class Traingle:Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Triangle Drawn ");
           
        }
    }

  static void Main(string[] args)
        {
            /* Testing Polymorphism */
 
            Shape[] s = new Shape[3];

            /* Polymorphic Objects */
           
/* creating Array with Different types of Objects */

            s[0] = new Circle();
            s[1] = new Ractangel();
            s[2] = new Traingle();
 
      Console.WriteLine("\n\nRuntime polymorphism test\n\n");

            for (int i = 0; i < 3; i++)
            {
                s[i].Draw();
            }

            Console.ReadKey();
        }


image1.gif

Explanation of the code:

Here we have created one base class called shape. We have inherited the shape class in to three derived classes called Rectangle, Circle and triangle. each contain method called Draw() .to achieve runtime polymorphism we need to declare the method as virtual which we want to call from each derived object .Now we want to call method draw of each object from same base class object .

By runtime polymorphism you can see we have built the array which containing different types of objects in same array. And in Finally main Method of the program we Called Draw () function of the different objects which were reside in same array .At runtime. Though we are calling Draw function from the base class object we can call method of Derived classes

Conclusion:

We have learnt how to achieve runtime polymorphism in Visual C#.
 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now