What is Polymorphism With Example Code

Polymorphism is a fundamental concept in object oriented programming OOP
that allows objects of different classes to be treated as objects of a common superclass.
It enables a single interface to represent multiple types of objects,
providing flexibility and extensibility in code design.



using System;
 
namespace ConsoleApp1
{
    // Base class
    class Shape
    {
        // Virtual method
        public virtual void Draw()
        {
            Console.WriteLine("Drawing a shape");
 
        }
    }
 
 
 
    // Derived class
    class Circle : Shape
    {
        // Override method
        public override void Draw()
        {
            Console.WriteLine("Drawing a circle");
        }
    }
 
 
 
    // Derived class
    class Rectangle : Shape
    {
        // Override method
        public override void Draw()
        {
           Console.WriteLine("Drawing a rectangle");
        }
    }
 
 
 
    class Program
    {
        static void Main(string[] args)
        {
            // Polymorphic behavior
            Shape[] shapes = new Shape[2];
            shapes[0] = new Circle();
            shapes[1] = new Rectangle();
 
            foreach (Shape shape in shapes)
            {
                shape.Draw(); // Calls the appropriate Draw method based on the actual object type
            }
        }
    }
}