Skip to content

Commit

Permalink
Document breaks due to preferring ReadOnlySpan over Span
Browse files Browse the repository at this point in the history
  • Loading branch information
jjonescz committed Dec 27, 2024
1 parent 98ea496 commit 953f776
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Assert.Equal([2], x); // previously Assert.Equal<T>(T[], T[]), now ambiguous wit
Assert.Equal([2], x.AsSpan()); // workaround
var y = new int[] { 1, 2 };
var s = new ArraySegment<int>(x, 1, 1);
var s = new ArraySegment<int>(y, 1, 1);
Assert.Equal(y, s); // previously Assert.Equal<T>(T, T), now ambiguous with Assert.Equal<T>(Span<T>, Span<T>)
Assert.Equal(y.AsSpan(), s); // workaround
```
Expand All @@ -39,11 +39,26 @@ static class C
public static void R<T>(IEnumerable<T> e) => Console.Write(1);
public static void R<T>(Span<T> s) => Console.Write(2);
// another workaround:
[OverloadResolutionPriority(1)]
public static void R<T>(ReadOnlySpan<T> s) => Console.Write(3);
}
```

For that reason, `ReadOnlySpan<T>` is generally preferred over `Span<T>` by overload resolution in C# 14.
In some cases, that might lead to compilation breaks,
for example when there are overloads for both `Span<T>` and `ReadOnlySpan<T>`, both taking and returning the same span type:

```cs
int[] x = new[0];
Span<ulong> y = MemoryMarshal.Cast<int, ulong>(x); // previously worked, now compilation error
Span<ulong> z = MemoryMarshal.Cast<int, ulong>(x.AsSpan()); // workaround
static class MemoryMarshal
{
public static ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span) => default;
public static Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span) => default;
}
```

When using C# 14 or newer and targeting a .NET older than `net10.0`
or .NET Framework with `System.Memory` reference,
there is a breaking change with `Enumerable.Reverse` and arrays:
Expand Down

0 comments on commit 953f776

Please sign in to comment.