Introduction
System.ReadOnlySpan<T> is a second variant of Span<T> with read-only access. It will work with immutable data types like System.String. In this blog, you will learn how to apply pattern matching on ReadOnlySpan.
Pattern Matching on ReadOnlySpan
Assume we have ReaOnlySpan, which is defined in below statement,
ReadOnlySpan<char> text = "Gowtham K";
We can have a condition check, as given below
if (text is "Gowtham K") {
Console.WriteLine($ "Yes it is {text}");
}
From the above statement, it's obvious that ReadOnlySpan will work with an immutable data type System.String.
Let's do pattern matching with ReadOnlySpan,
//Pattern Matching
if (text is['G', ..]) {
Console.WriteLine("Name Starts with G");
}
The above pattern in the condition statement will check whether the 'text' starts with 'G' and ignore the rest of the characters. So, the above statement will return true and print "Name Starts with G" in the console.
Summary
We have seen how to perform a Pattern matching on ReadOnlySpan<T>, it is one of the key features from C# 11. We will see more about C# 11 features in my future blogs.
Click here to download the source code from GitHub.
Happy Coding!!!