C#
Beginner
1 min read
Pattern Matching
Example
// Pattern matching examples
object[] items = { 42, "hello", 3.14, true, null!, new List<int> { 1, 2 } };
foreach (var item in items)
{
string result = item switch
{
int n when n > 0 => $"Positive int: {n}",
int n => $"Non-positive int: {n}",
string { Length: > 3 } s => $"Long string: {s}",
string s => $"Short string: {s}",
double d => $"Double: {d:F2}",
bool b => $"Bool: {b}",
null => "null value",
_ => $"Other: {item.GetType().Name}"
};
Console.WriteLine(result);
}
// Property pattern
record Person(string Name, int Age, string Country);
var alice = new Person("Alice", 30, "UK");
string category = alice switch
{
{ Age: < 18 } => "Minor",
{ Country: "UK", Age: >= 18 } => "UK Adult",
{ Age: >= 65 } => "Senior",
_ => "Adult"
};
Console.WriteLine(category); // "UK Adult"
// List pattern (C# 11)
int[] nums = { 1, 2, 3, 4, 5 };
bool matched = nums is [1, 2, .. var rest] && rest.Length > 0;
Console.WriteLine(matched); // True