List Pattern in C#: What It Is and How to Use It
list pattern in C# is a way to match elements inside lists or arrays by their order and content using pattern matching syntax. It lets you check if a list has specific elements or structure directly in switch or if statements.How It Works
The list pattern in C# allows you to look inside a list or array and check if it matches a certain shape or sequence of elements. Think of it like checking if a row of boxes contains specific items in a certain order. Instead of writing loops or manual checks, you describe the pattern you want to find.
For example, you can say: "I want a list where the first item is 1, the second is 2, and the rest can be anything." The list pattern makes this easy and readable by using square brackets and commas to separate elements, similar to how you write lists.
This feature is part of C# 11 and later, making pattern matching more powerful and expressive for collections.
Example
This example shows how to use the list pattern in a switch expression to identify different list shapes.
using System; class Program { static void Main() { int[] numbers = {1, 2, 3, 4}; string result = numbers switch { [1, 2, 3, 4] => "Exact match: 1, 2, 3, 4", [1, 2, ..] => "Starts with 1, 2", [.., 4] => "Ends with 4", [] => "Empty list", _ => "Other pattern" }; Console.WriteLine(result); } }
When to Use
Use the list pattern when you want to check if a list or array matches a specific sequence of elements without writing loops or manual checks. It is great for parsing input, validating data shapes, or handling different cases based on list content.
For example, if you receive commands as lists of strings, you can match the command structure easily. Or when processing data packets, you can check headers and footers by pattern matching.
Key Points
- The list pattern matches elements by position inside lists or arrays.
- It uses square brackets
[]with commas to separate elements. - Supports
..to match any number of elements in the middle or end. - Introduced in C# 11 for more expressive pattern matching.