What is Polymorphism in C#: Simple Explanation and Example
polymorphism means that objects of different classes can be treated as objects of a common base class, allowing methods to behave differently based on the actual object type. It enables one interface to control access to a variety of underlying forms (data types).How It Works
Polymorphism in C# works like a remote control that can operate many different devices. You press the same button, but the result depends on the device you are controlling. In programming, this means you can call the same method on different objects, and each object responds in its own way.
This happens because classes can inherit from a base class and override its methods. When you use a base class reference to point to a derived class object, the program decides at runtime which method to run. This is called dynamic dispatch or runtime polymorphism.
Example
This example shows a base class Animal with a method Speak. Two derived classes, Dog and Cat, override this method to make different sounds. The MakeAnimalSpeak method takes an Animal but calls the correct Speak method depending on the actual animal.
using System; class Animal { public virtual void Speak() { Console.WriteLine("Animal makes a sound"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } } class Cat : Animal { public override void Speak() { Console.WriteLine("Cat meows"); } } class Program { static void MakeAnimalSpeak(Animal animal) { animal.Speak(); } static void Main() { Animal myDog = new Dog(); Animal myCat = new Cat(); MakeAnimalSpeak(myDog); // Dog barks MakeAnimalSpeak(myCat); // Cat meows } }
When to Use
Use polymorphism when you want to write flexible and reusable code that works with different types of objects through a common interface. It is helpful in situations like:
- Designing systems with many related classes that share behavior but differ in details.
- Implementing plugins or modules where new types can be added without changing existing code.
- Handling collections of objects that behave differently but can be treated uniformly.
For example, in a game, you might have many characters that move differently but all respond to a Move command. Polymorphism lets you call Move on any character without knowing its exact type.
Key Points
- Polymorphism allows one method to work with different object types.
- It relies on inheritance and method overriding.
- It enables dynamic method calls decided at runtime.
- It helps write cleaner, more maintainable, and extensible code.