Runtime: Add ReadOnlySpan<T>(Span<T>) constructor

Created on 11 Dec 2017  路  3Comments  路  Source: dotnet/runtime

It would be very nice to add the constructor overload ReadOnlySpan<T>(Span<T>) to the list of constructors of ReadOnlySpan<T>.

Indeed, right now, it's not possible to have a method taking Span<T> as input and returning ReadOnlySpan<T> as output - the result being a fragment of the input. As a result, the logic end-up relying on "soft" immutability as Span<T> are returned (but never written to), as opposed to benefit from "hard" immutability, where writes would not even be possible.

api-suggestion area-System.Memory

All 3 comments

@vermorel, can you clarify the proposal? Span<T> instances are implicitly convertible to ReadOnlySpan<T> instances, so for example the below method should compile just fine.

public static ReadOnlySpan<byte> Foo(Span<byte> input) {
  return input.Slice(2, 5);
}

We also have AsReadOnlySpan extension method, if you cannot use an implicit operator for some reason:
https://github.com/dotnet/corefx/blob/master/src/System.Memory/ref/System.Memory.cs#L126
C# public static ReadOnlySpan<T> AsReadOnlySpan<T>(this Span<T> span)

@ahsonkhan Thanks a lot for pointing out the implicit conversion. I had not even realized that it was possible. Yes, it delivers exactly what I was seeking here.

Was this page helpful?
0 / 5 - 0 ratings