Polymorphism in C# allows objects to be treated as instances of their parent class. It enables you to perform a single action in different ways. There are two main types: method overriding and method overloading.
1. Method Overriding
Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class.
classAnimal
{
publicvirtualvoidMakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
classDog:Animal
{
publicoverridevoidMakeSound()
{
Console.WriteLine("The dog barks");
}
}
classCat:Animal
{
publicoverridevoidMakeSound()
{
Console.WriteLine("The cat meows");
}
}
// Usage
Animal myAnimal =newAnimal();
Animal myDog =newDog();
Animal myCat =newCat();
myAnimal.MakeSound();// Output: The animal makes a sound
myDog.MakeSound();// Output: The dog barks
myCat.MakeSound();// Output: The cat meows
Key Points:
Use virtual keyword in the base class method
Use override keyword in the derived class method
2. Method Overloading
Method overloading allows multiple methods in the same class with the same name but different parameters.
Methods must have the same name but different parameter lists
Return type alone is not enough to distinguish overloaded methods
Benefits of Polymorphism
Increases code reusability
Reduces complexity
Improves code flexibility and maintainability
Remember, polymorphism is a powerful feature in object-oriented programming. It allows you to write more flexible and scalable code by treating related objects in a uniform way.