Fix MA0103 code fix when the left operand is implicitly converted to a span

Merged
ME
2mo ago
+105-1

What

The MA0103 code fix builds the SequenceEqual receiver from LeftOperand.Syntax, which is the syntax before the implicit conversion to ReadOnlySpan<char>. Before C# 14 (first-class spans), the receiver of an extension method is not implicitly converted, so the fixed code does not compile:

// LangVersion <= 13
void A(ReadOnlySpan<char> s)
{
    _ = "a" == s;
}
  • Expected: code that compiles, e.g. _ = "a".AsSpan().SequenceEqual(s);
  • Actual: _ = "a".SequenceEqual(s); (CS1929)

Fix

When the left operand is an implicit conversion to the span type, the fixer makes the conversion explicit:

  • from a string: "a".AsSpan().SequenceEqual(s)
  • from any other type (e.g. char[], or a type with a user-defined conversion): ((ReadOnlySpan<char>)a).SequenceEqual(s)

The operands are not swapped, so they are still evaluated in the same order. The right operand is unchanged, because an argument is implicitly converted (s != "a" already becomes !s.SequenceEqual("a")).

Tests

  • Added StringEqualsSpan_CSharp12 and CharArrayEqualsSpan_CSharp12, which failed before the fix, and SpanNotEqualsString_CSharp12, which covers a converted right operand.
  • DoNotUseEqualityOperatorsForSpanOfCharAnalyzerTests: 6/6 passed on roslyn5.9 and roslyn4.8.