Polymorphism in C#

One interface, many forms - use a Car variable to drive SportsCar, Sedan, or Truck.

60-Second Version: Polymorphism = "many forms". Same method name Start() behaves differently for SportsCar vs Sedan. Code treats them all as Car.

1. Two Types of Polymorphism

Compile-time: Method Overloading - same name, different parameters

public void Print(string name) { Console.WriteLine(name); }
public void Print(int id) { Console.WriteLine(id); }

Runtime: Method Overriding - child changes parent behavior

public class Car
{
    public virtual void Start() { Console.WriteLine("Car starts"); }
}

public class SportsCar : Car
{
    public override void Start() { Console.WriteLine("VROOM!"); }
}

2. The Power: One Variable, Many Types

Car myCar = new SportsCar(); // Car variable, SportsCar object
myCar.Start(); // Output: VROOM! Calls SportsCar version

myCar = new Sedan(); // Same variable, different object
myCar.Start(); // Output: Car starts quietly. Calls Car version
Beginner Trap: Forgetting virtual in parent or override in child. Without both, polymorphism doesn't work. It will call parent version always.

Quick Check ๐Ÿง 

Next: Abstraction - Hiding complexity with abstract classes. Show only what matters.

Comments on Polymorphism (0)

No comments yet. Be the first to share your thoughts!