Pattern Matching
Inspect types and values with declarative patterns.
Introduction
Patterns combine type checks, extraction, and conditions without unsafe casts.
The switch expression handles null, positive integers, non-empty strings, and a final fallback in one exhaustive expression.
See how it works
Move the slider to change the day. The program jumps straight to the matching case, and to the default case when nothing matches.
Runnable C# example
Program.cs
using System;
class Program
{
static string Describe(object? value) => value switch
{
null => "missing",
int number when number > 0 => $"positive {number}",
string { Length: > 0 } text => $"text: {text}",
_ => "other"
};
static void Main() => Console.WriteLine(Describe(12));
}
positive 12Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Triangle Classification Classify three side lengths as invalid, equilateral, isosceles, or scalene. Easy
- Odd, Even, or Neither Classify a number by whether it is an odd integer, an even integer, or neither. Easy