Polymorphism is the ability of an object to take on many forms. In C#, polymorphism is achieved through inheritance and interfaces.

What is Polymorphism in C#

Inheritance allows derived classes to inherit properties and methods from their base classes. This allows objects of the derived class to be used wherever objects of the base class are expected. For example, if we have a base class called “Animal” and a derived class called “Dog”, we can use a “Dog” object anywhere we would use an “Animal” object.

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("The animal makes a sound");
    }
}
public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks");
    }
}
Animal animal = new Dog(); // Creating an instance of derived class
animal.MakeSound(); // Output: "The dog barks"

In this example, the “Dog” class is a derived class of the “Animal” class. It overrides the “MakeSound” method of the base class and provides its own implementation. When we create an instance of the “Dog” class and assign it to an “Animal” variable, we can call the “MakeSound” method and the implementation of the “Dog” class is used instead of the implementation of the “Animal” class.

Interfaces provide another way to achieve polymorphism in C#. An interface defines a set of methods and properties that a class must implement. This allows objects of different classes to be treated as the same type if they implement the same interface

Categorized in: