C# Polymorphism

Polymorphism is a concept in object-oriented programming where a single object can take different forms or have multiple behaviors. C# provides several ways to achieve polymorphism, such as method overloading, method overriding, and using interfaces.

Method Overloading

Method overloading is a feature in C# that allows multiple methods to have the same name but different parameters. This allows developers to use a single method name to perform different operations based on the type or number of parameters passed to the method.

1class Calculator 2{ 3 public int Add(int a, int b) 4 { 5 return a + b; 6 } 7 8 public int Add(int a, int b, int c) 9 { 10 return a + b + c; 11 } 12}

In the above example, the Add method is overloaded with two different parameters. The first method takes two integer parameters and returns their sum, while the second method takes three integer parameters and returns their sum.

Method Overriding

Method overriding is a feature in C# that allows a child class to provide a different implementation for a method that is already defined in its parent class. This is useful when we need to change the behavior of an inherited method without changing its name.

1class Animal 2{ 3 public virtual void MakeSound() 4 { 5 Console.WriteLine("The animal makes a sound"); 6 } 7} 8 9class Cat : Animal 10{ 11 public override void MakeSound() 12 { 13 Console.WriteLine("Meow"); 14 } 15}

In the above example, the Animal class has a virtual method MakeSound which is overridden in the Cat class with a different implementation. When we call the MakeSound method on a Cat object, it will print "Meow" instead of "The animal makes a sound".

Interfaces

An interface is a contract that specifies a set of methods and properties that a class must implement. In C#, we can use interfaces to achieve polymorphism by allowing objects of different classes to be treated as if they have the same behavior.

1interface IAnimal 2{ 3 void MakeSound(); 4} 5 6class Cat : IAnimal 7{ 8 public void MakeSound() 9 { 10 Console.WriteLine("Meow"); 11 } 12} 13 14class Dog : IAnimal 15{ 16 public void MakeSound() 17 { 18 Console.WriteLine("Woof"); 19 } 20}

In the above example, the Cat and Dog classes both implement the IAnimal interface which specifies a single method MakeSound. This allows us to call the MakeSound method on objects of either class as if they have the same behavior.