Polymorphism
Polymorphism comes from the Greek for “many forms”. It lets objects of different classes be treated as objects of a common superclass, through a shared interface (a base class or an interface). The specific method that runs depends on the actual type of the object at runtime. Polymorphism is often cited as the third pillar of OOP, after encapsulationEncapsulationKeep an object's data private, and let the outside world reach it only through members you choose.Opens in a new tab and inheritanceInheritanceA class that starts with everything another class has, and adds its own.Opens in a new tab.
Virtual members and overriding
Base class methods, properties, events or indexers declared as virtual or abstract can be overridden in derived classes with the override keyword. When such a member is invoked through a base class reference that points to a derived class object, the overridden version in the derived class runs. This is runtime polymorphism.
The base method is virtual, each derived class overrides it, and the commented usage calls it through a Shape reference.
public class Shape{ public virtual void Draw() { Console.WriteLine("Drawing a generic shape."); }}public class Circle : Shape{ public override void Draw() { Console.WriteLine("Drawing a circle."); }}public class Rectangle : Shape{ public override void Draw() { Console.WriteLine("Drawing a rectangle."); }} // Usage:// Shape myShape = new Circle();// myShape.Draw(); // Calls Circle.Draw() // Shape anotherShape = new Rectangle();// anotherShape.Draw(); // Calls Rectangle.Draw()Where it matters
Polymorphism is key to building flexible, extensible systems. It lets you write generic code that operates on objects of different types, as long as they share a common base type or implement a common interface. New types can be added to the system with minimal changes to the existing code that uses the abstraction.There is a look-alike that is not polymorphism: method hiding with newMethod hiding with newSame name in a derived class, but not an override.Opens in a new tab.
Sources
- C# Object Oriented (How It Works For Developers), IronPDF · accessed May 16, 2025
- Polymorphism, C#, Microsoft Learn · accessed May 16, 2025