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#:

    1. Compile-time (Static) Polymorphism

    2. 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

KeywordUse
virtualBase class method can be overridden
overrideDerived class method overrides base class
newHides base class method (not true polymorphism)

πŸ“Œ 5. Polymorphism Benefits

  1. Code Reusability β†’ Same method name for different behaviors

  2. Flexibility β†’ Works with different types of objects

  3. Maintainability β†’ Can add new derived classes without changing existing code

  4. Simplifies API β†’ Users don’t need to know exact class type


πŸ“Œ 6. Summary Table

TypeHow AchievedExample
Compile-Time (Static)Method OverloadingAdd(int,int) vs Add(double,double)
Run-Time (Dynamic)Method Overridingvirtual + override
Key ConceptSame name, different behaviorMakeSound() 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