🔀 Same Method, Different Behavior
Polymorphism lets objects behave differently. Virtual and override enable dynamic behavior. Loose coupling, extensible.
📝 Polymorphism Example
public class Shape
{
public virtual string GetName() => "Shape";
public virtual double GetArea() => 0;
}
public class Circle : Shape
{
public double Radius { get; set; }
public override string GetName() => "Circle";
public override double GetArea() => Math.PI * Radius * Radius;
}
public class Square : Shape
{
public double Side { get; set; }
public override string GetName() => "Square";
public override double GetArea() => Side * Side;
}
public class Triangle : Shape
{
public double Base { get; set; }
public double Height { get; set; }
public override string GetName() => "Triangle";
public override double GetArea() => 0.5 * Base * Height;
}
// Usage
List shapes = new List
{
new Circle { Radius = 5 },
new Square { Side = 4 },
new Triangle { Base = 3, Height = 6 }
};
foreach (var shape in shapes)
{
Console.WriteLine($"{shape.GetName()} area: {shape.GetArea()}");
}
🎯 Real-World Example
public abstract class PaymentProcessor
{
public abstract void ProcessPayment(decimal amount);
}
public class CreditCardProcessor : PaymentProcessor
{
public override void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing credit card payment: {amount:C}");
}
}
public class PayPalProcessor : PaymentProcessor
{
public override void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing PayPal payment: {amount:C}");
}
}
public class CryptoProcessor : PaymentProcessor
{
public override void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing crypto payment: {amount:C}");
}
}
// Payment service (decoupled)
public class OrderService
{
private readonly PaymentProcessor _processor;
public OrderService(PaymentProcessor processor)
{
_processor = processor;
}
public void Checkout(decimal amount)
{
_processor.ProcessPayment(amount);
}
}
// Dependency injection
services.AddScoped();
💡 Benefits
- Code works with different types
- Easy to add new types (open/closed principle)
- Loose coupling (depends on abstraction, not implementation)
- Testable (mock dependencies)
“Polymorphism made payment processing flexible. Added crypto payment without changing OrderService. Open/closed principle in action.”
