C# Tip : List Patterns

List patterns in C# (12 or above) allow you to match elements within a collection using pattern matching syntax. They help you check if a list has certain elements, a specific structure, or a particular number of items—making your code more readable and expressive when working with arrays or lists.

Example

Here's a simple example of list patterns in C#:

int[] numbers = { 1, 2, 3 };

if (numbers is [1, 2, 3])
{
    Console.WriteLine("Exact match: [1, 2, 3]");
}

Explanation:

  • The condition numbers is [1, 2, 3] checks if the array exactly matches the pattern: it has three elements, in the same order, with those exact values.

  • If it matches, the code inside the if block runs.

Partial match

You can also do partial matches:

if (numbers is [1, ..])
{
    Console.WriteLine("Starts with 1");
}
0
Subscribe to my newsletter

Read articles from Muralidharan Deenathayalan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Muralidharan Deenathayalan
Muralidharan Deenathayalan

I am a software architect with over a decade of experience in architecting and building software solutions.