Pattern matching lets you test a value against a pattern and extract information in one concise expression.
object obj = "Hello, World!";
if (obj is string s)
Console.WriteLine($"String of length {s.Length}");
if (obj is string { Length: > 5 } longStr)
Console.WriteLine($"Long string: {longStr}");
public static string Classify(object obj) => obj switch
{
int n when n < 0 => "negative int",
int n when n == 0 => "zero",
int n => $"positive int: {n}",
string s when s == "" => "empty string",
string s => $"string: {s}",
null => "null",
_ => "something else"
};
Console.WriteLine(Classify(-5)); // negative int
Console.WriteLine(Classify("hi")); // string: hi
Console.WriteLine(Classify(null)); // null
record Person(string Name, int Age, string Country);
static string GetDiscount(Person p) => p switch
{
{ Country: "US", Age: >= 65 } => "Senior US discount",
{ Country: "UK" } => "UK discount",
{ Age: < 18 } => "Youth discount",
_ => "No discount"
};
Console.WriteLine(GetDiscount(new Person("Alice", 70, "US")));
// Senior US discount
int[] arr = { 1, 2, 3 };
string result = arr switch
{
[] => "empty",
[var x] => $"one element: {x}",
[1, 2, ..] => "starts with 1, 2",
_ => "other"
};
Console.WriteLine(result); // starts with 1, 2