Skip to content

Polymorphism

Polymorphism allows objects of different types to be treated as objects of a common base type. It enables you to write code that can work with objects of multiple types through a common interface.

Method Overriding

Method overriding allows a derived class to provide a different implementation of a method defined in its base class. The base class method must be marked as virtual, and the derived class method must use the override keyword.

csharp
public class Shape
{
    public virtual double GetArea()
    {
        return 0;
    }
}

public class Circle : Shape
{
    public double Radius { get; set; }
    
    public override double GetArea()
    {
        return Math.PI * Radius * Radius;
    }
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }
    
    public override double GetArea()
    {
        return Width * Height;
    }
}

Runtime Polymorphism

Runtime polymorphism occurs when a base class reference is used to refer to a derived class object. The actual method that gets called is determined at runtime based on the actual type of the object.

csharp
Shape shape1 = new Circle { Radius = 5 };
Shape shape2 = new Rectangle { Width = 4, Height = 3 };

Console.WriteLine(shape1.GetArea()); // Uses Circle's implementation
Console.WriteLine(shape2.GetArea()); // Uses Rectangle's implementation