MSDN Documentation

C# Basics: Understanding Polymorphism

Polymorphism: The Many Forms of Objects

Polymorphism, a fundamental concept in object-oriented programming (OOP), allows us to treat objects of different classes in a uniform way if they share a common base class or interface. The term "polymorphism" itself comes from Greek, meaning "many forms." In C#, it enables you to write more flexible, extensible, and maintainable code.

Core Concepts of Polymorphism

Runtime vs. Compile-Time Polymorphism

C# supports two main types of polymorphism:

Runtime Polymorphism in Detail (Method Overriding)

Runtime polymorphism is where the true power of treating "many forms" comes into play. Consider a scenario with a base class Animal and derived classes like Dog and Cat.

Example: Animal Hierarchy

Let's define a base class Animal with a virtual method Speak.


public class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("The animal makes a sound.");
    }
}

public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("The dog barks: Woof!");
    }
}

public class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine("The cat meows: Meow!");
    }
}
                

Now, we can use polymorphism to treat a Dog or Cat object as an Animal:


public class Program
{
    public static void Main(string[] args)
    {
        Animal myAnimal1 = new Dog(); // Dog object treated as an Animal
        Animal myAnimal2 = new Cat(); // Cat object treated as an Animal
        Animal genericAnimal = new Animal();

        myAnimal1.Speak(); // Output: The dog barks: Woof!
        myAnimal2.Speak(); // Output: The cat meows: Meow!
        genericAnimal.Speak(); // Output: The animal makes a sound.

        // Using a collection of Animals
        List<Animal> animals = new List<Animal>();
        animals.Add(new Dog());
        animals.Add(new Cat());
        animals.Add(new Animal());

        foreach (Animal animal in animals)
        {
            animal.Speak(); // Calls the appropriate Speak() method at runtime
        }
        // Output:
        // The dog barks: Woof!
        // The cat meows: Meow!
        // The animal makes a sound.
    }
}
                

Key Benefits of Polymorphism

Abstract Classes and Interfaces for Polymorphism

While virtual and override are powerful, abstract classes and interfaces enforce a stricter contract and are often preferred for defining polymorphic behavior.

Polymorphism is a cornerstone of robust object-oriented design in C#. By mastering its principles, you can write significantly more adaptable and efficient software.