skip to content

Why can recompiling unchanged C# code with C# 14 make an array argument bind to a Span<T> or ReadOnlySpan<T> overload, and what can that break?

level: seniorimportance: should knowfreq 20%

answer

  1. new built-in conversions
  2. arrays now convert to spans
  3. covariant arrays meet Span<T>
  4. expression trees and ref structs

basics

~20 s

C# 14 adds implicit conversions from arrays to Span<T> and ReadOnlySpan<T>, so span overloads become applicable and can win. Calls can turn ambiguous, covariant arrays can throw ArrayTypeMismatchException, and expression trees can bind MemoryExtensions.Contains, which the interpreter rejects.

solid answer

~40 s

C# 14's first-class spans make an array convert implicitly to `Span<T>` and `ReadOnlySpan<T>`, including as an extension-method receiver and during type inference. Overloads C# 13 ignored now compete, so the same source can bind elsewhere. Three effects: a call can become ambiguous, error CS0121, when a span overload ties with an array one; a `Span<T>` overload can beat an `IEnumerable<T>` one, and a covariant array (a `string[]` held as `object[]`) then throws `ArrayTypeMismatchException` in the `Span<T>` constructor, which is why overload resolution now generally prefers `ReadOnlySpan<T>`; and inside an expression tree `array.Contains(x)` binds to `MemoryExtensions.Contains`, which `Compile(preferInterpretation: true)` cannot run and query providers must recognise. Fixes: `AsEnumerable()`, `AsSpan()`, an explicit static call such as `Enumerable.Contains(array, x)`, or `[OverloadResolutionPriority]` on the library side.

code

csharp · 17 lines
csharp
string[] merchantIds = ["M-001", "M-002"];
object[] items = merchantIds; // array covariance

try
{
    Audit.Record(items);
}
catch (ArrayTypeMismatchException ex)
{
    Console.WriteLine(ex.GetType().Name);
}

static class Audit
{
    public static void Record<T>(IEnumerable<T> entries) => Console.WriteLine("IEnumerable<T> overload");
    public static void Record<T>(Span<T> entries) => Console.WriteLine("Span<T> overload");
}

go deeper

for a junior

Know that C# 14 lets arrays convert to Span<T> and ReadOnlySpan<T> implicitly, and that this can change which method a call reaches.

for a middle

Explain why built-in conversions, unlike the old user-defined ones, apply to extension receivers and type inference, and what AsEnumerable() or AsSpan() changes.

for a senior

Diagnose the three symptoms after an upgrade: CS0121 ambiguity, ArrayTypeMismatchException from covariant arrays, and expression trees that bind MemoryExtensions.Contains.

for a principal

Weigh first-class spans as an upgrade risk for code that builds expression trees or exposes overloaded APIs, and decide which tests must pass before the language version moves.

## What changed in C# 14 `Span<T>` and `ReadOnlySpan<T>` are **ref structs**: stack-only views over contiguous memory such as an array. Before C# 14 the conversion from `T[]` to a span was a **user-defined implicit operator** declared on the span types. User-defined conversions do not apply to extension-method receivers and do not help generic type inference, so in practice span overloads were often invisible when the argument was an array. C# 14 ("first-class spans") makes these **built-in conversions** in the language: - `T[]` to `Span<T>` and to `ReadOnlySpan<T>`; - `Span<T>` to `ReadOnlySpan<T>`; - `string` to `ReadOnlySpan<char>`. Built-in conversions take part in extension-method lookup and type inference. The result is what the feature intends, since one `ReadOnlySpan<T>` extension now serves arrays and spans alike, but it also means **overload resolution sees new candidates in old code**. Recompiling unchanged source as C# 14 can pick a different method. Roslyn's "Compiler Breaking Changes - DotNet 10" document and the .NET 10 compatibility article on span overloads list the cases. ## Three ways the new binding shows up | Symptom | Typical code | Why | Workaround | |---|---|---|---| | New compile error **CS0121** | `Equal([2], longs)` with `Equal<T>(T[], T[])` and `Equal<T>(ReadOnlySpan<T>, Span<T>)` | a span overload became applicable and neither is better | pass `longs.AsSpan()`, or the author adds `[OverloadResolutionPriority]` | | **`ArrayTypeMismatchException`** at run time | `R(objects)` with `R<T>(IEnumerable<T>)` and `R<T>(Span<T>)`, where `objects` is a `string[]` typed `object[]` | `Span<T>` wins; its constructor rejects a covariant array | `objects.AsEnumerable()`, or offer a `ReadOnlySpan<T>` overload | | **Exception from an interpreted expression tree** | `Expression<Func<int[], int, bool>> e = (a, n) => a.Contains(n);` | binds to `MemoryExtensions.Contains`; the interpreter cannot handle a ref struct | `Enumerable.Contains(a, n)`, or cast `a` to `IEnumerable<int>` | ## The covariant-array trap **Array covariance** lets a `string[]` be stored in an `object[]` variable. Writing an `int` into it would corrupt the array, so the runtime checks every write. The `Span<T>` constructor does the same check up front: the runtime's source documents that it throws `ArrayTypeMismatchException` when the array is covariant and its type is not exactly `T[]`. `ReadOnlySpan<T>` cannot write, so it has no such check. That is why C# 14's rules **generally prefer `ReadOnlySpan<T>` over `Span<T>`** when both apply, and why a library that adds a read-only overload is safer than one that adds a writable one. ## Expression trees and query providers An **expression tree** is code captured as data: the compiler binds the method calls at compile time and stores them in the tree. Under C# 14 the stored call for `a.Contains(n)` is `MemoryExtensions.Contains` over a `ReadOnlySpan<int>`, not `Enumerable.Contains`. Two consumers notice: - `Expression<TDelegate>.Compile(preferInterpretation: true)` runs the tree in an interpreter that does not support ref structs, and throws (an `ArgumentException` on .NET 10). `Compile()` without interpretation still works when the runtime can generate code. - A LINQ provider that translates trees, such as an ORM's SQL translator, sees a method it may not recognise, and must either learn it or fail the query. ## `Enumerable.Reverse` and unsupported configurations On targets older than `net10.0`, C# 14 makes `array.Reverse()` bind to `MemoryExtensions.Reverse`, which reverses **in place** and returns `void`, instead of `Enumerable.Reverse`, which returns a new sequence. .NET 10 added `Enumerable.Reverse<TSource>(this TSource[])`, which wins on `net10.0`, so the break only hits C# 14 used on an older target, a combination the compiler's notes call unsupported. ## Finding them during an upgrade 1. Treat new **CS0121** errors after the upgrade as span-related until proven otherwise; the fix is an explicit `AsSpan()` or `AsEnumerable()`. 2. Search for `Expression<` lambdas that call `Contains`, `SequenceEqual` or similar on arrays, and test the code paths that interpret or translate them. 3. Look for APIs taking both `IEnumerable<T>` and `Span<T>` that may receive covariant arrays. 4. A .NET 8 to .NET 10 move crosses C# 13 as well, whose collection-expression overload changes are listed in the .NET 9 breaking-change document. 5. When a call must keep its old target, make it explicit at the call site (`AsEnumerable()`, a cast to the interface, or a static call); that documents the intent and survives the next language release. How each conversion works in everyday span code is the subject of the lesson on spans; here the point is that the release changed which overload old code binds to.

  • Why does C# 14 generally prefer `ReadOnlySpan<T>` over `Span<T>` when both apply?
    Converting an array to a writable `Span<T>` must check the array's exact element type, and a covariant array, such as a `string[]` held in an `object[]` variable, fails that check with `ArrayTypeMismatchException`. `ReadOnlySpan<T>` cannot write and has no such check. Roslyn's breaking-change notes give this as the reason for the preference.
  • Does `amounts.Reverse()` on an `int[]` change meaning in a net10.0 project?
    No. .NET 10 added `Enumerable.Reverse<TSource>(this TSource[])`, which beats `MemoryExtensions.Reverse` over a span, so the call still returns a reversed sequence and leaves the array alone. The in-place, `void`-returning reverse only appears with C# 14 on older targets, an unsupported configuration.
  • How can a library author keep callers on the intended overload after C# 14?
    Add `[OverloadResolutionPriority]` (C# 13, .NET 9) to the overload that should win; among candidates declared in the same type, those with a lower priority are dropped before the compiler picks the best one. Roslyn's notes name it as the API-author workaround, alongside offering `ReadOnlySpan<T>` rather than `Span<T>` parameters.

  • Recompiling with a newer C# never changes which overload an existing call binds to.
  • The new span conversions only matter for code that already uses Span<T>.
  • An ArrayTypeMismatchException after the upgrade must be a .NET 10 runtime bug.
  • Expression trees are unaffected because they are data, not compiled calls.
  • Rewriting every array argument with AsSpan() is the only workaround.

Assumes C# 14 on .NET 10, which made array-to-span conversions built in; C# 13 and earlier bind these calls to the non-span overloads.