Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ReadOnlySpan<T> not have an overload for Slice(...) that accepts a Range instance?

Tags:

c#

.net

As I've gotten more familiar with ReadOnlySpan<T> and friends, I've really come to wonder why there is no overload of Slice() that accepts a Range. Specifically when one is using ReadOnlySpan<T>.Split(...), one ends up with a set of Range instances, and from there, it is (in my opinion) clunky to turn the Range instances into something more useful. For example:

// make a span
var myInput = "ab,cd,ef".AsSpan();

// set up a span to hold the ranges from the Split() call
Span<Range> splitRanges = stackalloc Range[3];

// split the span based on commas
myInput.Split(splitRanges, ',');

// get the offset and length of the first range
var (offset, length) = splitRanges[0].GetOffsetAndLength(myInput.Length);

// slice the original span based on the first range's values
var firstSpan = myInput.Slice(offset, length);

Am I missing something? Is there a more concise, or even more idiomatic way to accomplish this?

like image 593
Mark Avatar asked Oct 26 '25 14:10

Mark


1 Answers

Because you can already use a Range to access a ReadOnlySpan<T> just like you would with a Span<T>, a string, or an array:

var firstSpan = myInput[splitRanges[0]];

It's not documented as such, because it uses the "implicit range support" feature, which, in short, will turn that into a call to Slice. So adding a Slice overload that takes a Range would have been redundant.

like image 73
Etienne de Martel Avatar answered Oct 29 '25 03:10

Etienne de Martel