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.
Let's talk
I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.
I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.