Skip to content

List patterns C# 11

Context: List patterns (C# 11) allow matching arrays or lists against a sequence of elements.

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

Use .. to match any number of elements.

int[] arr = { 1, 2, 3, 4, 5 };
if (arr is [1, .., 5])
{
Console.WriteLine("Starts with 1, ends with 5");
}

Command line argument parsing: Match args array with list patterns (e.g., ["--help"], ["--output", .. var rest]).

Example: In System.CommandLine, you could implement custom parsing with list patterns.