Polymorphism, derived from Greek words meaning "many forms," is a fundamental concept in object-oriented programming (OOP). In C#, polymorphism allows objects of different classes to be treated as objects of a common base class. This enables you to write more flexible, extensible, and reusable code.
Polymorphism is typically achieved through two main mechanisms:
Method overriding is a runtime polymorphism technique. It occurs when a derived class inherits a method from its base class and provides its own specific implementation for that method. To enable overriding, the base class method must be declared with the virtual or abstract keyword, and the derived class method must be declared with the override keyword.
Base Class:
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("This is the base class method.");
}
}
Derived Class:
public class DerivedClass : BaseClass
{
public override void Display()
{
Console.WriteLine("This is the derived class method.");
}
}
using System;
public abstract class Shape
{
public abstract double Area(); // Abstract method, must be overridden
}
public class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public override double Area()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public override double Area()
{
return Width * Height;
}
}
public class Program
{
public static void Main(string[] args)
{
// Using polymorphism: a collection of base class pointers
// pointing to derived class objects.
Shape[] shapes = new Shape[2];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 6.0);
foreach (Shape shape in shapes)
{
// The correct Area() method is called at runtime
// based on the actual object type.
Console.WriteLine($"Area: {shape.Area()}");
}
}
}
Area: 78.53981633974483
Area: 24
Polymorphism is closely related to abstract classes and interfaces:
Both abstract classes and interfaces are powerful tools for enforcing polymorphism and designing robust OOP systems.
For more detailed information and advanced scenarios, please refer to the official Microsoft Docs on Polymorphism.