IntermediateLesson 11 of 16
Pattern Matching – C#
Elegantly test and deconstruct types, properties and structures.
Pattern matching tests values by shape: type, constants, ranges, properties, lists. With the switch expression it becomes a compact, readable case distinction.
Console.WriteLine(Beschreibe(42)); // number 42
Console.WriteLine(Beschreibe(-5)); // negative number -5
Console.WriteLine(Beschreibe("Hello")); // text with 5 characters
Console.WriteLine(Beschreibe(null)); // nothing
static string Beschreibe(object? o) => o switch
{
null => "nothing",
int n when n < 0 => $"negative number {n}",
int n => $"number {n}",
string { Length: 0 } => "empty text",
string s => $"text with {s.Length} characters",
_ => "unknown"
};Property patterns test properties directly, and relational patterns (<, >=) and and/or/not combine conditions:
Console.WriteLine(Rabatt(new("Ada", 70, true))); // 30
Console.WriteLine(Rabatt(new("Bob", 30, true))); // 20
Console.WriteLine(Rabatt(new("Cem", 16, false))); // 10
Console.WriteLine(Rabatt(new("Dan", 40, false))); // 0
static int Rabatt(Kunde k) => k switch
{
{ Premium: true, Alter: >= 65 } => 30,
{ Premium: true } => 20,
{ Alter: < 18 or >= 65 } => 10,
_ => 0
};
record Kunde(string Name, int Alter, bool Premium);Tuples and lists can be matched too (list patterns since C# 11), and is is suitable for individual checks:
Console.WriteLine(Spiel("Rock", "Scissors")); // Player 1
Console.WriteLine(Spiel("Paper", "Paper")); // Draw
int[] daten = { 1, 2, 3, 4 };
Console.WriteLine(daten is [1, .., 4]); // True
object o = "Hello World";
if (o is string s && s.Length > 3)
Console.WriteLine(s.ToUpper()); // HELLO WORLD
if (o is not null) Console.WriteLine("not null");
static string Spiel(string a, string b) => (a, b) switch
{
("Rock", "Scissors") or ("Scissors", "Paper") or ("Paper", "Rock") => "Player 1",
_ when a == b => "Draw",
_ => "Player 2"
};TipThe compiler warns if a
switch expression does not cover all cases (e.g. with enums or sealed hierarchies). The discard case _ covers the rest.