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.
C# supports two main types of 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.
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");
}
}
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
Polymorphism is often used in conjunction with abstract classes and interfaces to create more robust and flexible designs.
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.