C# List Pattern — Complete Guide
In this tutorial, you'll learn about C# List Pattern. We cover key concepts, practical examples, and best practices.
You need to check whether an array starts with certain elements, has a specific length, or contains a pattern. You write index checks and length checks scattered through your code. List patterns let you match the shape of a collection in a single expression.
Wrong
public string ClassifyArray(int[] numbers)
{
if (numbers.Length >= 2 && numbers[0] == 1 && numbers[1] == 2)
return "Starts with 1, 2";
if (numbers.Length == 0)
return "Empty";
return "Other";
}
Output: Works but verbose and error-prone with index management.
Right
public string ClassifyArray(int[] numbers) => numbers switch
{
[1, 2, ..] => "Starts with 1, 2",
[] => "Empty",
[var first, ..] => $"Starts with {first}",
_ => "Other"
};
Output: "Starts with 1, 2" for [1, 2, 3, 4], "Empty" for [], "Starts with 5" for [5, 6].
List patterns work with arrays, lists, spans, and any type that is Countable and Indexable. Use .. for the slice pattern to match zero or more remaining elements.
Prevention
- Use list patterns for array/list shape matching instead of manual index checks.
- Use
[..]to match any non-empty collection without caring about specific elements. - Use
[]for empty collection checks. - Use
[var first, .. var rest]to decompose head and tail. - Use nested patterns:
[ { Type: "admin" }, .. ]for object arrays. - Combine list patterns with other pattern types (type, property, positional) for complex collection matching.
Common Mistakes with list pattern
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
List patterns are used in Doda Browser to parse URL path segments. For more C# patterns, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro