Tools
Log in
English

Learn to codeC#

C# polymorphism

Based on C# 12switch expression · C# 8+{ Target: > 20 } · C# 9+

One DailyKwh() call, many devices: C# virtual calls plus is and switch patterns.

In one line

Handling many child objects through one parent type, so that the same method call runs whatever behavior each object overrides.

Why you need it

Writing if (d is Lamp) ... else if (d is Heater) ... in every loop because devices compute power differently means hunting down all those places for each new device.

Move the calculation into each class’s override and the loop shrinks to d.DailyKwh(). Keep a switch pattern in one place only for messages that truly depend on the type.

Everyday picture

Think of a wall socket. It gives the same power without asking what is plugged in. A lamp makes light, a heater makes heat, a speaker makes sound. Each reacts in its own way to the same "switch on", and that is polymorphism.

Example code

Program.cs · 60 lines
List<Device> devices = [new Lamp("Desk lamp", 9), new Heater("Heater", 1500, 22), new Device("Speaker", 20)];double total = 0;foreach (Device d in devices){    double kwh = d.DailyKwh();    total += kwh;    Console.WriteLine($"{d.Name,-10} {kwh,5:F2} kWh  {Hint(d)}");}Console.WriteLine($"Total {total:F2} kWh"); static string Hint(Device d) => d switch{    Heater { Target: > 20 } h => $"set it to {h.Target - 2}C",    Lamp => "use daylight",    _ => "ok",}; class Device{    public string Name { get; }    public int Watts { get; }     public Device(string name, int watts)    {        Name = name;        Watts = watts;    }     public virtual double HoursPerDay => 4;     public virtual double DailyKwh()    {        return Watts * HoursPerDay / 1000;    }} class Lamp : Device{    public Lamp(string name, int watts) : base(name, watts)    {    }     public override double HoursPerDay => 6;} class Heater : Device{    public int Target { get; }     public Heater(string name, int watts, int target) : base(name, watts)    {        Target = target;    }     public override double DailyKwh()    {        double hours = Target > 20 ? 5 : 3;        return Watts * hours / 1000;    }}

When to use it

  • Many kinds of things, one piece of code to handle them (devices, shapes, payment methods, notices)
  • Places where new kinds show up often
  • When only some wording differs by type, collect it in one switch expression

An is pattern (d is Heater h) checks and declares a variable in one step. as gives null on failure, so you still need a null check.

When the same pattern matching repeats in several places, it is time to move that behavior into a virtual method.

Common mistakes

Casting with ( ) without checking

If the object is not of that type, the program stops with an InvalidCastException. is Heater h checks and converts in one step and simply gives false otherwise.

Wrong

List<Device> all = [new Lamp("Desk", 9), new Heater("Mini", 800, 18)];var h = (Heater)all[0];Console.WriteLine(h.Target);

When you run itUnhandled exception. System.InvalidCastException: Unable to cast object of type 'Lamp' to type 'Heater'.

Fixed

List<Device> all = [new Lamp("Desk", 9), new Heater("Mini", 800, 18)];if (all[0] is Heater h){    Console.WriteLine(h.Target);}else{    Console.WriteLine($"{all[0].Name} is not a heater");}

When you run itDesk is not a heater

Putting the broad arm first

A switch expression tries arms from the top. With Device first, a heater is caught there too, so the compiler reports the later arm as unreachable. Put narrow types first and _ last.

Wrong

Console.WriteLine(Kind(new Heater("Mini", 800, 18))); static string Kind(Device d) => d switch{    Device => "device",    Heater => "heater",};

What the C# compiler sayserror CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.

Fixed

Console.WriteLine(Kind(new Heater("Mini", 800, 18))); static string Kind(Device d) => d switch{    Heater => "heater",    _ => "device",};

When you run itheater

Comparing types with GetType() ==

GetType() == typeof(Lamp) is true only for that exact type, so SmartLamp, which inherits from Lamp, is missed. Ask "this type or a child of it" with is Lamp.

Wrong

List<Device> all = [new Lamp("Desk", 9), new SmartLamp("Hall", 7)];int lamps = all.Count(d => d.GetType() == typeof(Lamp));Console.WriteLine($"lamps: {lamps}"); class SmartLamp(string name, int watts) : Lamp(name, watts);

When you run itlamps: 1

Fixed

List<Device> all = [new Lamp("Desk", 9), new SmartLamp("Hall", 7)];int lamps = all.Count(d => d is Lamp);Console.WriteLine($"lamps: {lamps}"); class SmartLamp(string name, int watts) : Lamp(name, watts);

When you run itlamps: 2

Check yourself

Question 1

A heater set to 18 degrees sits in a Device variable. What does DailyKwh() print?

Device d = new Heater("Mini", 800, 18);Console.WriteLine(d.DailyKwh());

Show the answer

Answer: 2. 2.4 Whatever the variable type, the object’s override (Heater) runs. The target is 20 or less, so 3 hours: 800 × 3 / 1000 = 2.4. The parent version would have used 4 hours and given 3.2.

Question 2

What does the switch expression return?

object x = 42;string size = x switch{    int n when n > 40 => "big",    int => "small",    _ => "not a number",};Console.WriteLine(size);

Show the answer

Answer: 1. big 42 is an int and when n > 40 holds, so the first arm wins. Only the first matching arm from the top is used.

Questions people ask

Does pattern matching replace polymorphism?

They do different jobs. Put behavior that differs per type in each class with virtual and override; collect logic that branches on type in one place only (messages, logging) in a switch pattern.

What is the difference between is and as?

is returns true or false and can declare a variable, as in d is Heater h. as returns null on failure, so you still need a null check. Modern code mostly uses is patterns.

What does _ mean in a switch expression?

It is the catch-all arm for values no earlier arm matched. Leave it out and the compiler warns; an unmatched value at run time throws an exception.