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 = [newLamp("Desk lamp", 9), newHeater("Heater", 1500, 22), newDevice("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");staticstringHint(Device d) => d switch{Heater { Target: > 20 } h => $"set it to {h.Target - 2}C",Lamp => "use daylight", _ => "ok",};classDevice{publicstringName { get; }publicintWatts { get; }publicDevice(string name, int watts) {Name = name;Watts = watts; }publicvirtualdoubleHoursPerDay => 4;publicvirtualdoubleDailyKwh() {returnWatts * HoursPerDay / 1000; }}classLamp : Device{publicLamp(string name, int watts) : base(name, watts) { }publicoverridedoubleHoursPerDay => 6;}classHeater : Device{publicintTarget { get; }publicHeater(string name, int watts, int target) : base(name, watts) {Target = target; }publicoverridedoubleDailyKwh() {double hours = Target > 20 ? 5 : 3;returnWatts * hours / 1000; }}
C# code does not run on this page. Run your edited code on your own computer with dotnet run.
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 = [newLamp("Desk", 9), newHeater("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 = [newLamp("Desk", 9), newHeater("Mini", 800, 18)];if (all[0] isHeater 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.
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.
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.
List<Device> all = [newLamp("Desk", 9), newSmartLamp("Hall", 7)];int lamps = all.Count(d => d isLamp);Console.WriteLine($"lamps: {lamps}");classSmartLamp(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 = newHeater("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.