Using The New Generics Pattern Matching Feature In .NET 7

Introduction

Microsoft has just released .NET 7 on 14th November 2022. In other articles, we looked at some of the new features.

Today, we will look at another feature introduced with .NET 7 and that is generics pattern matching. Let us begin.

The generics pattern matching feature

Let us create a console application using Visual Studio 2022 Community edition.

Using the new generics pattern matching feature in .NET 7

Using the new generics pattern matching feature in .NET 7

Now, add the below code to the “Program.cs” file:

// Generic list of string type
var genericList = new List<string>() { "Munib","Butt" };

Console.WriteLine(genericList is ["Munib", "Butt"]);
Console.WriteLine(genericList is ["John", "Smith"]);

// Generic list of int type
var genericListIntegers = new List<int>() { 100,200,300,400 };

Console.WriteLine(genericListIntegers is [100, 200, 300, 400]);
Console.WriteLine(genericListIntegers is [>99, >199, >299, >399]);
Console.WriteLine(genericListIntegers is [> 99, > 199, > 299, > 499]);

When you run this application, you get the below,

Using the new generics pattern matching feature in .NET 7

Here, we see that we have created two generic lists. The first one is of string type and we assigned two values to it. Then we matched the values. In the first case, we get True because the values matched the pattern. However, in the second case, we get False as the values did not match the pattern. To better explain the use of pattern matching, we can look at the second generic list which is of Int type. Here we see that we can match the exact values or even conditions. If all match correctly, we get a True result or else false. In the last pattern matched, the last value is “400” which does not satisfy the condition for this element which states that it must be “>499” and hence whole pattern match returns a False.

Summary

In this article, we looked at a new feature that has been introduced with .NET 7. Using the pattern matching feature we can validate patterns in generic lists and also arrays. In the next article, we will look into another feature of .NET 7.


Similar Articles