skip to content

In C#, why can `method == "GET"` return false for a ReadOnlySpan<char> sliced from a log line, and how do you compare span contents?

level: middleimportance: should knowfreq 38%

answer

  1. same memory, not same text
  2. the operator compares references
  3. literals can fool tests
  4. SequenceEqual or Equals with comparison
  5. Equals(object) throws

basics

~20 s

The == operator on spans checks whether both point at the same memory with the same length, not whether they hold the same characters. Compare contents with SequenceEqual, MemoryExtensions.Equals with a StringComparison, or the constant pattern span is "GET".

solid answer

~30 s

`ReadOnlySpan<T>`'s `==` is documented in the source as true only when both spans "point at the same memory and have the same length"; it does not look at the contents. `method == "GET"` compiles because the literal converts to a `ReadOnlySpan<char>`, but the slice points into the log line and the literal points at a different string, so the result is false. To compare text use `method.SequenceEqual("GET")` (element by element, ordinal for `char`), `method.Equals("get", StringComparison.OrdinalIgnoreCase)`, or the C# 11 constant pattern `method is "GET"`. Spans also do not support `Equals(object)` or `GetHashCode()`: both throw `NotSupportedException`, and `string.GetHashCode(ReadOnlySpan<char>)` hashes the contents instead.

code

csharp · 13 lines
csharp
string line = "GET /api/orders 200";
ReadOnlySpan<char> method = line.AsSpan(0, 3);

Console.WriteLine(method == "GET");                       // False: different memory
Console.WriteLine(method.SequenceEqual("GET"));           // True: same chars
Console.WriteLine(method.Equals("get", StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(method is "GET");                       // True: constant pattern
Console.WriteLine(method == line.AsSpan(0, 3));           // True: same start, same length

int[] a = [1, 2, 3];
int[] b = [1, 2, 3];
Console.WriteLine(a.AsSpan() == b.AsSpan());              // False
Console.WriteLine(a.AsSpan().SequenceEqual(b));           // True

go deeper

for a junior

Remember that == on a span asks whether two views point at the same memory; it is not a text comparison.

for a middle

Explain the identity semantics, why literal interning makes the bug pass in tests, and the three content comparisons: SequenceEqual, Equals with StringComparison and the constant pattern.

for a senior

Spot span == in code review as a likely bug, check which comparison the protocol needs, and know that Equals(object) and GetHashCode throw NotSupportedException.

for a principal

Consider an analyzer or review rule for span equality in parsing code, since the compiler accepts the identity comparison silently.

## What == means on a span For `string`, `==` compares characters, so many C# developers carry that expectation over to `ReadOnlySpan<char>`. It does not hold. In `Span.cs` and `ReadOnlySpan.cs` the operator is defined, and commented, as: > Returns true if left and right point at the same memory and have the same length. Note that this does *not* check to see if the *contents* are equal. So `==` on spans is an **identity** check on the view: same starting reference, same length. Two spans over two different arrays holding `1, 2, 3` are not equal; two slices of the same array at the same offset and length are. ## Why the bug hides in tests ```csharp ReadOnlySpan<char> lit = "GET"; Console.WriteLine(lit == "GET"); // True ReadOnlySpan<char> method = line.AsSpan(0, 3); Console.WriteLine(method == "GET"); // False ``` The first comparison is true for the wrong reason: identical string literals in one assembly are interned into a single string object, so both spans happen to start at the same memory. A unit test built from literals passes. In production the span is sliced from a line read off the network, a different string, and the comparison is false for every request. Nothing warns: the code compiles because `"GET"` converts to `ReadOnlySpan<char>` and the operator applies. ## Comparing contents correctly | Need | Call | Notes | |---|---|---| | Exact match, element by element | `span.SequenceEqual(other)` | `MemoryExtensions.SequenceEqual<T>` where `T : IEquatable<T>?`; for `char` that is ordinal | | Case-insensitive or culture-aware text | `span.Equals(other, StringComparison.OrdinalIgnoreCase)` | `MemoryExtensions.Equals(ReadOnlySpan<char>, ReadOnlySpan<char>, StringComparison)` | | Match against a constant string | `span is "GET"` | Constant pattern on `ReadOnlySpan<char>` and `Span<char>`, since C# 11 | | Prefix or suffix | `span.StartsWith("/api/", StringComparison.Ordinal)` | Pass the comparison; text rules are covered with string comparison | | Hash the text, for example for a custom table | `string.GetHashCode(ReadOnlySpan<char>)` | Gives the same hash as the equal string within a process | A `switch` on a span can use the same constant patterns: `method switch { "GET" => ..., "POST" => ..., _ => ... }` compares contents, which makes it the readable choice for routing on a verb. ## Equals and GetHashCode throw Spans override the two `object` members only to block them: - `Equals(object? obj)` throws `NotSupportedException` with the message "Equals() on Span and ReadOnlySpan is not supported. Use operator== instead." - `GetHashCode()` throws `NotSupportedException`: "GetHashCode() on Span and ReadOnlySpan is not supported." Both are marked `[Obsolete]` and hidden from IntelliSense. The reason is that a span cannot be boxed, so an `object`-based equality contract makes no sense for it. Note what the first message recommends: `operator==`, the identity check, not a content check. ## A code-review checklist When a pull request touches span-based parsing, read every comparison on a span with these questions: - Is `==` or `!=` applied to two spans or to a span and a string literal? If so, is the author really asking "same memory?" If not, it is a bug, however green the tests are. - Do the tests build their input from literals only? Add one case that builds the input at run time, for example with `string.Concat` or by reading from a `StringReader`, so interning cannot hide the problem. - Is any span compared by calling `Equals` with a single argument? On a span, a one-argument call resolves to `Equals(object)`, which throws, not to a content comparison. - Is the comparison kind explicit? A bare `StartsWith("x")` on a `ReadOnlySpan<char>` resolves to the generic element-wise overload, which is ordinal; writing `StringComparison.Ordinal` makes the intent visible to the next reader. ## Choosing the right comparison 1. Ask whether you mean **same memory** or **same text**. Same memory is rare: checking that a slice still covers a buffer you handed out, for example. 2. For text, pick the comparison deliberately: ordinal for protocol tokens like HTTP verbs and header names, a culture-aware comparison only for text people read. 3. Do not round-trip through `ToString()` just to use `==`; that allocates and hides the decision. ## Interview angle The strong answer quotes the semantics (same memory, same length), explains why a literal-based test passes, and offers `SequenceEqual`, `Equals` with `StringComparison` or a constant pattern as the fix. Knowing that `Equals(object)` throws shows that the candidate has read the type rather than guessed from `string`.

  • When is span == actually the comparison you want?
    When identity is the question: you want to know whether two spans are the same view of the same buffer, for instance to check that a parser returned a slice of the input rather than a copy, or to detect that a caller passed back the exact span you handed out. For any question about text or values, use a content comparison.
  • How do you use a sliced ReadOnlySpan<char> as a key to look up a string-keyed Dictionary<string, int>?
    You cannot pass the span to the ordinary indexer, and the span has no usable GetHashCode. On .NET 9 and later, `dictionary.GetAlternateLookup<ReadOnlySpan<char>>()` returns a lookup that hashes and compares the span's characters with the dictionary's comparer. On older runtimes you call `ToString()` on the slice, paying one allocation per lookup.

  • Says span == compares characters the way string == does.
  • Trusts a span comparison because a test using literals passed.
  • Calls span.Equals((object)other) and expects a content comparison.
  • Converts both spans with ToString just to compare them.
  • Believes SequenceEqual on ReadOnlySpan<char> ignores case.