C# 11- List Pattern Matching

Introduction:

  The pattern matching was introduced with C# 7 from then it’s kept on evolving and now with C# 11 we got a new feature called List pattern matching. The list pattern is to check, if sequence elements match corresponding nested patterns.

 The expression/statement like is, switch will support pattern matching.

List Pattern Matching:

For example, I have defined an array of integers as given below,

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

List patterns also applies to array, basically it applies to anything that is countable or it has a count property.

We can patten match this array using is expression.

Console.WriteLine(numbers is [1, 2, 3]); // True 

The above statement will return true, since it’s matched the pattern

Console.WriteLine(numbers is [1, 2, 4]); // False
Console.WriteLine(numbers is [1, 2, 3,4]); // False

The above statements will return false, since it’s doesn’t match the pattern.

We can use the operator in the List pattern, as given below

Console.WriteLine(numbers is [0 or 1, <= 2, <= 3]);//True

The above statement will return true

You can discard the value in the array using ’_’, as given below

Console.WriteLine(numbers is [1, _, _]);//True

The above statement will return true

List Pattern with switch statement:
var emptyName=Array.Empty<string>();
var myName = new[] { "Gowtham" };
var text = emptyName switch
{
    [] => "Name was empty",
    [var fullName] => $"My Name is{fullName},"
};
Console.WriteLine(text);

The above code snippet will match the list pattern and print “Name was empty” in console, since we passing an empty array.

var text = myName switch
{
    [] => "Name was empty",
    [var fullName] => $"My Name is {fullName}"
};

The above code snippet will match the list pattern and print “My Name is Gowtham” in console, since we passing an myName array.

Summary:

 We have seen what is List pattern matching and how to use it with is and switch expressions/statement in C# 11. This list pattern matching is certainly limited in use cases but it can be pretty handy.

Happy Coding 🧑‍💻

GitHub- Source code

gowthamk91

Leave a Reply

Discover more from Gowtham K

Subscribe now to keep reading and get access to the full archive.

Continue reading