Lesson 16 of 40
Core C#
Intermediate
โฑ 30 min
Pattern Matching & Switch Expressions
Write elegant conditional logic using C#'s powerful pattern matching โ type patterns, property patterns, list patterns, and exhaustive switch expressions.
Part 1: Type & Property Patterns
object shape = GetShape();
double area = shape switch
{
Circle { Radius: var r } => Math.PI * r * r,
Rectangle { Width: var w, Height: var h } => w * h,
null => throw new ArgumentNullException(),
_ => throw new NotSupportedException()
};
double area = shape switch
{
Circle { Radius: var r } => Math.PI * r * r,
Rectangle { Width: var w, Height: var h } => w * h,
null => throw new ArgumentNullException(),
_ => throw new NotSupportedException()
};
Part 2: List Patterns (C# 11+)
int[] nums = [1,2,3];
var desc = nums switch
{
[] => "empty",
[var x] => $"single: {x}",
[var first, .., var last] => $"first={first}, last={last}",
};
var desc = nums switch
{
[] => "empty",
[var x] => $"single: {x}",
[var first, .., var last] => $"first={first}, last={last}",
};
Part 3: Relational & Logical Patterns
string ClassifyAge(int age) => age switch
{
< 0 => throw new ArgumentOutOfRangeException(),
<= 12 => "Child",
> 12 and <= 17 => "Teenager",
>= 65 => "Senior",
_ => "Adult"
};
{
< 0 => throw new ArgumentOutOfRangeException(),
<= 12 => "Child",
> 12 and <= 17 => "Teenager",
>= 65 => "Senior",
_ => "Adult"
};
Part 4: Pattern Matching with is
// Declaration pattern
if (obj is string { Length: > 0 } s)
Console.WriteLine($"Non-empty string: {s}");
// Negation pattern
if (obj is not null and not string)
Console.WriteLine("Not null and not a string");
if (obj is string { Length: > 0 } s)
Console.WriteLine($"Non-empty string: {s}");
// Negation pattern
if (obj is not null and not string)
Console.WriteLine("Not null and not a string");
C# in Visual Studio 2026
๐ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition