In Object-Oriented Programming (OOP), polymorphism is one of the four core principles (along with inheritance, encapsulation, and abstraction). In C#, polymorphism allows you to treat different types of objects in the same way, which makes your code more flexible and extensible.
Let’s break it down simply and see how it works in real-world applications and in actual C# code.
What is polymorphism?
"Poly" means "many."
"Morphism" comes from the Greek word "morphḗ" + "ism." The meaning of morphḗ is "form/shape."
There are two main types of polymorphism in C#:
-
Compile-Time Polymorphism (Static) – Achieved through method overloading.
-
Run-Time Polymorphism (Dynamic) – Achieved through method overriding using inheritance.
Advantages of Polymorphism:
Real-Time Example of Polymorphism
Imagine you run a payment processing system. You have different types of payment methods: CreditCard, PayPal, and UPI. Each payment method processes the payment differently, but from the user's perspective, they just call a MakePayment()
function.
This is polymorphism: different classes implement the same method in their own way.
Coding Example in C#
Compile-Time Polymorphism (Method Overloading)
Run-Time Polymorphism
using System;
namespace PolymorphismExample
{
// Base class
public class Payment
{
public virtual void MakePayment()
{
Console.WriteLine("Processing generic payment...");
}
}
// Derived class 1
public class CreditCard : Payment
{
public override void MakePayment()
{
Console.WriteLine("Processing payment through Credit Card.");
}
}
// Derived class 2
public class PayPal : Payment
{
public override void MakePayment()
{
Console.WriteLine("Processing payment through PayPal.");
}
}
// Derived class 3
public class UPI : Payment
{
public override void MakePayment()
{
Console.WriteLine("Processing payment through UPI.");
}
}
class Program
{
static void Main(string[] args)
{
Payment[] payments = new Payment[]
{
new CreditCard(),
new PayPal(),
new UPI()
};
foreach (Payment payment in payments)
{
payment.MakePayment(); // Calls the appropriate method depending on object type
}
}
}
}
How It Works
-
The base class
Payment
defines a virtual methodMakePayment()
. -
Derived classes override the method with their own specific implementations.
-
At runtime, C# decides which
MakePayment()
method to call based on the object type — this is run-time polymorphism.
Why Use Polymorphism?
-
Makes code more maintainable and scalable
-
Encourages code reuse through inheritance
-
Helps you follow SOLID principles, especially the Open/Closed Principle
-
Useful when working with interfaces or base classes to handle a variety of behaviors