16 November
C# 11 – Pattern matching on Spans
Programming
min. read

Let’s list all the features that C# 11 brings to the table. Let’s discuss them all one by one, with their use cases, and see how they can come in handy. At the bottom of each article, you can find a link to all 14 new C# features!
Pattern matching on Spans
As you saw in the “List patterns” article, we can pattern-match numbers, but C# 11 extends this support for Spans and constants.
ReadOnlySpan<char> name = "Tomasz Juszczak";
if (name is "Tomasz Juszczak")
{
Console.WriteLine("Yes it was");
}
but we can also do this when we want to match let’s say only the first character
ReadOnlySpan<char> name = "Tomasz Juszczak";
if (name is ['T', ..])
{
Console.WriteLine("Name starts with T");
}
This obviously will also work with other features like in the example below
ReadOnlySpan<char> name = "Tomasz Juszczak";
if (name is ['T' or 'A', .. var rest])
{
Console.WriteLine($"Name starts with T or A and the remaining characters are {rest}");
}
Further reading at dotnet GitHub page.
Author
About prog
Founded in 2016 in Warsaw, Poland. Prographers mission is to help the world put the sofware to work in new ways, through the delivery of custom tailored 3D and web applications to match the needs of the customers.
SIMILAR POSTS
C# 11 – Everything you need to know
Programming
min. read
C# 11 – Improved method group
Programming
min. read
C# 11 – Auto-default struct
Programming
min. read