Letβs go through polymorphism in C# β another core concept of object-oriented programming (OOP).
π 1. What is Polymorphism?
Polymorphism means βmany formsβ. In C#, it allows a single interface or method to have different behaviors depending on the object or context.
-
Enables flexible and reusable code
-
Often works together with inheritance
-
Two main types in C#:
-
Compile-time (Static) Polymorphism
-
Run-time (Dynamic) Polymorphism
-
π 2. Compile-Time Polymorphism (Method Overloading)
-
Same method name with different parameters
-
Determined at compile time
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;
}
// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(2, 3)); // 5
Console.WriteLine(calc.Add(2.5, 3.5)); // 6
Console.WriteLine(calc.Add(1, 2, 3)); // 6
- Same method name, different parameters β compiler decides which one to call
π 3. Run-Time Polymorphism (Method Overriding)
-
Method behavior is determined at runtime
-
Uses inheritance + virtual/override keywords
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Some generic sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark!");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
// Usage
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.MakeSound(); // Bark!
a2.MakeSound(); // Meow!
- Same method (
MakeSound
) behaves differently depending on the object type
π 4. Key Keywords
Keyword | Use |
---|---|
virtual | Base class method can be overridden |
override | Derived class method overrides base class |
new | Hides base class method (not true polymorphism) |
π 5. Polymorphism Benefits
-
Code Reusability β Same method name for different behaviors
-
Flexibility β Works with different types of objects
-
Maintainability β Can add new derived classes without changing existing code
-
Simplifies API β Users donβt need to know exact class type
π 6. Summary Table
Type | How Achieved | Example |
---|---|---|
Compile-Time (Static) | Method Overloading | Add(int,int) vs Add(double,double) |
Run-Time (Dynamic) | Method Overriding | virtual + override |
Key Concept | Same name, different behavior | MakeSound() behaves differently for Dog/Cat |
β Tip:
-
Use compile-time polymorphism for convenience and readability
-
Use run-time polymorphism to leverage inheritance and allow objects to behave differently dynamically