Polymorphism means "many forms." In C#, it lets a derived class change how a base class method works — while keeping the same method name. The right method gets called based on the actual object type, even if you're holding it through a base class reference.
virtual and override
Mark a base class method as virtual to allow overriding. Then use override in the derived class to provide a new implementation.
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Some sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark!");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
Polymorphism in Action
The real magic: you can treat all animals the same way, and each one does its own thing.
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound();
myCat.MakeSound();
Both variables are typed as Animal, but calling MakeSound() on each runs the overridden version. The dog barks, the cat meows.
Overriding vs Hiding
If you don't use override, the derived class method hides the base method instead of overriding it. You'll get a warning from the compiler.
class Dog : Animal
{
public new void MakeSound()
{
Console.WriteLine("Bark!");
}
}
Animal a = new Dog();
Dog d = new Dog();
a.MakeSound();
d.MakeSound();
With hiding (using new), a.MakeSound() calls the base version because the variable type is Animal. With override, it would call the derived version. Override respects the actual object type; hiding looks at the variable type.
Why Polymorphism Matters
You can write code that works on a base class and automatically handles all derived types. Add a new derived class tomorrow, and the existing code works without changes. That's the power — code that's open for extension but closed for modification.
static void MakeItSound(Animal animal)
{
animal.MakeSound();
}
MakeItSound(new Dog());
MakeItSound(new Cat());