How does polymorphism work in C#

Polymorphism is one of the four fundamental principles of Object-Oriented Programming (OOP) in C#. It allows objects to be treated as instances of their parent class, enabling a single interface to represent different underlying forms (data types). This is particularly useful in method overriding and interface implementation.

In C#, polymorphism can be achieved through two primary means: method overriding and interfaces. When a derived class provides a specific implementation for a method that is already defined in its base class, polymorphism allows that derived class to be used interchangeably with the base class.

Here's an example to illustrate polymorphism using method overriding:

public class Animal { public virtual void Speak() { Console.WriteLine("An animal makes a sound"); } } public class Dog : Animal { public override void Speak() { Console.WriteLine("Woof!"); } } public class Cat : Animal { public override void Speak() { Console.WriteLine("Meow!"); } } public class Program { public static void Main(string[] args) { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.Speak(); // Output: Woof! myCat.Speak(); // Output: Meow! } }

polymorphism C# object-oriented programming method overriding interfaces