Polymorphism in C#
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. In C#, it enables you to write more flexible and extensible code.
Types of Polymorphism
C# supports two main types of polymorphism:
- Compile-time polymorphism (Method Overloading)
- Runtime polymorphism (Method Overriding)
Runtime Polymorphism
Runtime polymorphism is achieved through method overriding and is the focus of this guide. It allows a derived class to provide a specific implementation of a method that is already defined in its base class.
Virtual and Override Keywords
To implement runtime polymorphism in C#, we use the virtual keyword in the base class and the override keyword in the derived class.
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");
}
}
Using Polymorphism
Polymorphism allows us to use a base class reference to call methods on derived class objects:
Animal myAnimal = new Dog();
myAnimal.MakeSound(); // Output: The dog barks
Benefits of Polymorphism
- Code reusability and flexibility
- Easier maintenance and extensibility
- Ability to work with objects at a more abstract level
Abstract Classes and Interfaces
Polymorphism is often used in conjunction with abstract classes and interfaces to create more robust and flexible designs.
Best Practices
- Use polymorphism to create flexible and extensible code
- Avoid overusing virtual methods, as they can impact performance
- Consider using interfaces for multiple inheritance scenarios
- Always provide a base implementation or make the method abstract if there's no sensible default
Conclusion
Polymorphism is a powerful feature in C# that allows for more flexible and maintainable code. By understanding and applying polymorphism effectively, you can create more robust and scalable applications.
To further enhance your C# skills, explore related concepts such as inheritance and interfaces.