Polymorphism means different objects can respond in their own way when you call a method with the same name on them. You mark the method virtual in the base class, and derived classes can override it.
csharp
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog says: woof");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat says: meow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound();
myCat.MakeSound();
}
}What to watch out for
Animal myDog = new Dog();holds it as the base type, but the method that actually runs is the override defined in Dog.- This concept is a lifesaver for patterns like plugin systems, payment providers, and notification channels.
You should see
The dog says: woof The cat says: meow