Assume we have a span which points to a sub-range of an array.
Is there any way to grow this span, assuming the initial underlying array has enough capacity to do so? (Assuming we can't use
Example:
int[] array = new int[]{4, 17, 0, 2, 3, 16, 1};
var span = new Span<int>(array);
var s1 = span.Slice(0, 1);
// Assume we can't use "array" directly here anymore, but only s1
var s2 = s1.Slice(0, 2); // bang! Argument of ouf range exception, even though array would have enough capacity
Not safely -- the Span doesn't know how large the underlying array is.
One unsafe option is to use MemoryMarshal:
var s2 = MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(s1), 7);
We use GetReference to get a ref int variable which points to the first element in the array, and pass that to CreateSpan with an explicit length.
You can write to arbitrary memory if you get the length wrong, so be careful!
There might be a way to try and get the original array back out of the Span, and then query its length, but I can't find one. MemoryMarshal.TryGetArray takes a Memory, not a Span.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With