Skip to content

Commit 642ee01

Browse files
authored
Document breaks due to preferring ReadOnlySpan over Span (#76572)
1 parent f7e10cf commit 642ee01

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Assert.Equal([2], x); // previously Assert.Equal<T>(T[], T[]), now ambiguous wit
1919
Assert.Equal([2], x.AsSpan()); // workaround
2020
2121
var y = new int[] { 1, 2 };
22-
var s = new ArraySegment<int>(x, 1, 1);
22+
var s = new ArraySegment<int>(y, 1, 1);
2323
Assert.Equal(y, s); // previously Assert.Equal<T>(T, T), now ambiguous with Assert.Equal<T>(Span<T>, Span<T>)
2424
Assert.Equal(y.AsSpan(), s); // workaround
2525
```
@@ -39,11 +39,26 @@ static class C
3939
public static void R<T>(IEnumerable<T> e) => Console.Write(1);
4040
public static void R<T>(Span<T> s) => Console.Write(2);
4141
// another workaround:
42-
[OverloadResolutionPriority(1)]
4342
public static void R<T>(ReadOnlySpan<T> s) => Console.Write(3);
4443
}
4544
```
4645

46+
For that reason, `ReadOnlySpan<T>` is generally preferred over `Span<T>` by overload resolution in C# 14.
47+
In some cases, that might lead to compilation breaks,
48+
for example when there are overloads for both `Span<T>` and `ReadOnlySpan<T>`, both taking and returning the same span type:
49+
50+
```cs
51+
double[] x = new double[0];
52+
Span<ulong> y = MemoryMarshal.Cast<double, ulong>(x); // previously worked, now compilation error
53+
Span<ulong> z = MemoryMarshal.Cast<double, ulong>(x.AsSpan()); // workaround
54+
55+
static class MemoryMarshal
56+
{
57+
public static ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span) => default;
58+
public static Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span) => default;
59+
}
60+
```
61+
4762
When using C# 14 or newer and targeting a .NET older than `net10.0`
4863
or .NET Framework with `System.Memory` reference,
4964
there is a breaking change with `Enumerable.Reverse` and arrays:

0 commit comments

Comments
 (0)