Skip to content

Pattern match Span on string constants C# 11.0performancereadability

Use pattern matching to compare a Span of characters against a string literal.

When working with Span<char> or ReadOnlySpan<char> for zero-allocation string processing, comparing against known string values required calling MemoryExtensions.SequenceEqual or similar methods.

C# 11 allows you to use is and switch to pattern match a Span<char> or ReadOnlySpan<char> directly against a string constant.

This is primarily a readability and correctness feature. A ReadOnlySpan<char> cannot be compared with == against a string - the operator is not defined - so the old approach was a chain of MemoryExtensions.SequenceEqual calls or a hand-written comparison. The constant pattern lets the same switch expression you would write for a string work directly on a span, which removes the chance of an off-by-one in a length check or a missing branch.

The comparison is ordinal and case-sensitive, matching the semantics of == on string.

Code ​

csharp
static int ParseCommand(ReadOnlySpan<char> command) => command switch
{
    "start" => 1,
    "stop" => 2,
    "reset" => 3,
    _ => -1
};
csharp
static int ParseCommand(ReadOnlySpan<char> command)
{
    if (command.SequenceEqual("start")) return 1;
    if (command.SequenceEqual("stop")) return 2;
    if (command.SequenceEqual("reset")) return 3;
    return -1;
}

Notes ​

  • Works with both Span<char> and ReadOnlySpan<char>, and in is expressions as well as switch expressions and statements
  • The constant must be a string literal or a const string - it cannot be a runtime string variable
  • Matching is ordinal and case-sensitive; use MemoryExtensions.Equals with a comparison type when you need case-insensitivity
  • No allocation happens on the match path, so this is safe inside a parser's inner loop
  • Pairs well with [StringSyntax]-style parsing helpers and list patterns C# 11.0 when the input arrives as a span

More information ​

Powered by Intracia