SkillPilotAI

Polymorphism

Polymorphism means one call with different behaviour depending on the object. In C# runtime polymorphism comes from virtual + override, compile-time polymorphism from overloading, and casting lets you move between base and derived types safely.

15.1 The problem: the card fee is never added

C#
Print(new Payment { Amount = 1000 });Print(new CardPayment { Amount = 1000 });static void Print(Payment p) =>    Console.WriteLine(p.Total());class Payment{    public decimal Amount { get; set; }    public decimal Total() => Amount * 1.18m;}class CardPayment : Payment{    public decimal Total()        => Amount * 1.18m + 20;}
Output
$ dotnet run Payment.csPayment.cs(12,20): warning CS0108:  'CardPayment.Total()' hides inherited  member 'Payment.Total()'.1180.001180.00
  • A call to a normal (non-virtual) method is fixed at compile time by the variable type.
  • p is declared as Payment, so Payment.Total() runs even though the object is a CardPayment.
  • We need the decision at runtime, based on the actual object.

15.2 Fix: virtual + override

  • virtual in the base: derived classes may override this method.
  • override in the derived class gives its own version.
  • base.Total() reuses the base GST logic, then adds 20; the 18% rule stays in one place.
C#
Print(new Payment { Amount = 1000 });Print(new CardPayment { Amount = 1000 });static void Print(Payment p) =>    Console.WriteLine(p.Total());class Payment{    public decimal Amount { get; set; }    public virtual decimal Total()        => Amount * 1.18m;}class CardPayment : Payment{    public override decimal Total()        => base.Total() + 20;}
Output
$ dotnet run Payment.cs1180.001200.00

15.3 How it works: virtual dispatch

How the runtime picks the method
  1. 1.Code calls p.Total()

  2. 2.Runtime checks the actual object inside p

  3. 3.CardPayment overrides Total -> its version runs

  4. 4.No override -> the base version runs

  5. 5.Result: Payment 1180, Card 1200

Runtime polymorphism = virtual dispatch

15.4 Hiding with the new keyword

  • Base method not virtual + same-named method in the derived class = method hiding (warning CS0108).
  • new only silences the warning; it does not fix the bug.
  • The same object gives two answers: the variable type decides.
C#
var card = new CardPayment { Amount = 1000 };Payment p = card;Console.WriteLine($"card: {card.Total()}");Console.WriteLine($"p:    {p.Total()}");class Payment{    public decimal Amount { get; set; }    public decimal Total() => Amount * 1.18m;}class CardPayment : Payment{    public new decimal Total()        => Amount * 1.18m + 20;}
Output
$ dotnet run Hide.cscard: 1200.00p:    1180.00

15.5 Overloading (compile-time polymorphism)

  • Same name, different parameters: Total() and Total(decimal discount).
  • The compiler picks the method from the arguments at compile time.
  • Total(50): GST on 950 = 1121.00.
C#
var pay = new Payment { Amount = 1000 };Console.WriteLine(pay.Total());Console.WriteLine(pay.Total(50)); class Payment{    public decimal Amount { get; set; }    public virtual decimal Total()        => Amount * 1.18m;    public decimal Total(decimal discount)        => (Amount - discount) * 1.18m;}
Output
$ dotnet run Overload.cs1180.001121.00

15.6 Comparison: overriding vs hiding vs overloading

PointOverridingHiding (new)Overloading
SignatureSameSameDifferent parameters
Keywordsvirtual + overridenewNone
DecidedAt runtime, by the actual objectAt compile time, by the variable typeAt compile time, by the arguments
PolymorphismRuntimeNot reallyCompile time
Card examplep.Total() -> 1200p.Total() -> 1180Total(50) -> 1121

15.7 Upcasting and downcasting

  • Upcast: CardPayment stored in a Payment variable; automatic, because every CardPayment is a Payment.
  • The object does not change: GetType() still says CardPayment; only the variable type changed.
  • p.Last4 does not compile (Payment has no Last4); downcast with (CardPayment)p to get it back.
C#
Payment p = new CardPayment { Amount = 1000 };Console.WriteLine(p.GetType().Name);// p.Last4 -> error, Payment has no Last4var card = (CardPayment)p;Console.WriteLine(card.Last4);class Payment{    public decimal Amount { get; set; }}class CardPayment : Payment{    public string Last4 { get; set; } = "4242";}
Output
$ dotnet run Cast.csCardPayment4242

15.8 Checkpoint: a wrong downcast

C#
Payment p = new UpiPayment { Amount = 1000 };var card = (CardPayment)p;Console.WriteLine(card.Last4);
Output
$ dotnet run Check.csUnhandled exception.System.InvalidCastException: Unable to cast  object of type 'UpiPayment'  to type 'CardPayment'.   at Program.<Main>$(String[] args)   in Check.cs:line 2
  • The build passes: for the compiler p is a Payment that could be a card.
  • The runtime checks every downcast; a UPI object is not a card -> InvalidCastException.

15.9 Safe downcast: is and as

  • p is CardPayment card: checks the type and gives a typed variable in one step.
  • p as CardPayment: returns null on failure instead of throwing.
C#
Payment p = new UpiPayment();if (p is CardPayment card)    Console.WriteLine($"Card {card.Last4}");else    Console.WriteLine("Not a card");var c2 = p as CardPayment;Console.WriteLine(c2 is null);class Payment { }class UpiPayment : Payment { }class CardPayment : Payment{    public string Last4 { get; set; } = "4242";}
Output
$ dotnet run Safe.csNot a cardTrue
Choosing a cast
  1. 1.Derived -> base? Upcast, automatic and always safe

  2. 2.Base -> derived, 100% sure of the type? (CardPayment)p

  3. 3.Not sure? if (p is CardPayment card) { ... }

  4. 4.Want null instead of an exception? p as CardPayment

  5. 5.Wrong (T)p cast -> InvalidCastException at runtime

15.10 Common mistakes

  • A chain of if (p is CardPayment) ... else if (p is UpiPayment): every new type adds another if. Put the logic in a virtual Total() and just call p.Total().
  • Thinking upcasting loses data: the object stays the same; GetType() is still CardPayment and a downcast gives Last4 back.
  • Using new (hiding) to silence CS0108 instead of virtual/override.
  • Downcasting with (T) without checking first.
C#
// Right: each class owns its Totalstatic decimal Total(Payment p)    => p.Total(); class CardPayment : Payment{    public override decimal Total()        => base.Total() + 20;}// New type = just a new override

15.11 Interview tips

  • Polymorphism = one call, different behaviour; C# has compile-time (overloading) and runtime (virtual + override).
  • With virtual/override, a call through a base-type variable runs the override of the actual object.
  • new hides, it does not override: the variable type decides.
  • Downcast safely with the is pattern (or as); a wrong (T) cast throws InvalidCastException.