1.9 — Polymorphism¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.8 Interfaces · Next: 1.10 Generics
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- Polymorphism means one name, many behaviours.
- Compile-time polymorphism = method overloading. The compiler picks based on the arguments you passed.
- Runtime polymorphism = method overriding. The runtime picks based on what the object actually is.
The concept¶
The word comes from Greek: poly = many, morph = shape. "Many shapes."
In practice it means you can write one piece of code that works correctly with many different types, without knowing in advance which one it will get.
A simple picture: think of the word "draw". You can draw a circle, draw a square, draw a triangle. Same instruction, different result depending on what you are drawing. You do not need a separate word for each shape.
C# gives you two flavours, and interviewers usually want you to name both.
How it works¶
Compile-time polymorphism (overloading)¶
Several methods share a name but take different parameters. The compiler works out which one you meant by looking at the arguments at the call site.
public class Calculator
{
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;
public int Add(int a, int b, int c) => a + b + c;
}
calc.Add(1, 2); // picks the first — two ints
calc.Add(1.5, 2.5); // picks the second — two doubles
calc.Add(1, 2, 3); // picks the third — three ints
This is decided before the program ever runs. By the time the code executes, the decision is already baked in. That is why it is called compile-time (or "static") polymorphism.
What counts as a different overload: the number of parameters, their types, or their order.
What does NOT count: the return type. This is a common exam-style question:
public int GetValue() => 1;
public string GetValue() => "1";
// ERROR. You cannot overload on return type alone.
The reason is simple — if you write GetValue(); on its own line and ignore the result,
the compiler would have no way to know which one you meant.
Operator overloading is also compile-time polymorphism. See 1.19.
Runtime polymorphism (overriding)¶
This is the more important kind. A base class declares a virtual method, derived classes
override it, and the runtime picks the right version based on what the object actually
is.
public abstract class Shape
{
public abstract double Area();
}
public class Circle(double radius) : Shape
{
public override double Area() => Math.PI * radius * radius;
}
public class Rectangle(double w, double h) : Shape
{
public override double Area() => w * h;
}
Now the payoff:
List<Shape> shapes =
[
new Circle(1),
new Rectangle(2, 3),
new Circle(5)
];
double total = shapes.Sum(s => s.Area());
// Each s.Area() call runs the RIGHT version automatically.
// This loop has no idea circles or rectangles exist.
Look at that last line closely. The code says s.Area() where s is just a Shape. It
does not check the type. It does not have an if or a switch. Yet each object runs its
own correct calculation.
And this is the real benefit: if you add a Triangle class tomorrow, this loop keeps
working with no changes at all. That is polymorphism paying for itself.
Compare with what you would otherwise write:
// The version WITHOUT polymorphism — every new shape means editing this
double total = 0;
foreach (var s in shapes)
{
if (s is Circle c) total += Math.PI * c.Radius * c.Radius;
else if (s is Rectangle r) total += r.Width * r.Height;
// ...and you must remember to come back here for every new shape
}
A long chain of type checks like this is a strong hint that polymorphism is the better answer. This is also what the open/closed principle in SOLID is about — see 22.1.
Interfaces give you polymorphism too¶
You do not need inheritance. An interface works just as well:
public interface IPaymentMethod { Task PayAsync(decimal amount); }
public class CreditCard : IPaymentMethod { /* ... */ }
public class PayPal : IPaymentMethod { /* ... */ }
// Works with any payment method, present or future
async Task Checkout(IPaymentMethod method, decimal amount)
=> await method.PayAsync(amount);
This is usually the preferred approach in modern C#, because it does not force your types into an inheritance hierarchy.
Code¶
Putting both kinds together:
public abstract class Notifier
{
// Runtime polymorphism — each subclass sends differently
public abstract Task SendAsync(string recipient, string message);
// Compile-time polymorphism — three convenient ways to call it
public Task SendAsync(User user, string message)
=> SendAsync(user.Email, message);
public Task SendAsync(IEnumerable<User> users, string message)
=> Task.WhenAll(users.Select(u => SendAsync(u, message)));
}
public class EmailNotifier(IEmailSender sender) : Notifier
{
public override Task SendAsync(string recipient, string message)
=> sender.SendAsync(recipient, "Notification", message);
}
public class SmsNotifier(ISmsGateway gateway) : Notifier
{
public override Task SendAsync(string recipient, string message)
=> gateway.SendTextAsync(recipient, message);
}
Now calling code just holds a Notifier and calls SendAsync. It does not know or care
whether an email or a text message goes out.
Interview questions¶
Q: What is polymorphism?
It means one name can behave in different ways depending on the context. C# has two forms. Compile-time polymorphism is method overloading — several methods share a name but take different parameters, and the compiler picks the right one from the arguments. Runtime polymorphism is method overriding — a base class declares a virtual method, derived classes override it, and the runtime picks the version matching the actual object. The second one is the important one, because it lets you write code that works with types that did not exist when you wrote it.
Q: What is the difference between overloading and overriding?
Overloading is several methods with the same name in the same class, differing by their parameters, resolved by the compiler before the program runs. Overriding is a derived class replacing a virtual method from its base class, resolved by the runtime based on the actual object. So overloading is about convenience at the call site, and overriding is about substituting behaviour.
Q: Can you overload a method by changing only the return type?
No. If you called the method and ignored its result, the compiler would have no information to decide which one you meant. Overloads have to differ by the number, types, or order of their parameters.
Q: How does polymorphism help in real code?
It lets you write code that works with future types. If I have a list of shapes and call
Area() on each one, I never have to touch that loop again when someone adds a new shape.
Without it, you end up with a growing chain of type checks that has to be updated in every
place whenever a new type appears — and eventually someone forgets one. That is exactly
what the open/closed principle is warning about.
Traps ⚠️¶
newdoes not give you polymorphism. It hides the base method, and which version runs depends on the variable's declared type, not the object. See 1.7.- A method must be
virtualorabstractto be overridden. Marking itoverridein the derived class is not enough on its own. - Overload resolution can surprise you. When you pass a
null, or a type that could convert to several parameter types, the compiler picks by rules that are not always obvious. Cast explicitly when it is ambiguous. - Long
if (x is TypeA) ... else if (x is TypeB)chains usually mean polymorphism was the better design. - Polymorphism is not free at runtime. A virtual call costs a lookup. It is almost
never worth worrying about, but it is why
sealedcan help in genuinely hot code.
Related¶
- 1.7 Inheritance —
virtual,overrideand thenewtrap - 1.8 Interfaces — polymorphism without inheritance
- 1.17 Pattern matching — when type checking IS the right answer
- 1.19 Operator overloading — another form of compile-time polymorphism
- 22.1 SOLID — open/closed and Liskov substitution
- 22.5 Strategy pattern — polymorphism as a design pattern