I have a List
containing some data. I would like to pass it to a function which accepts ReadOnlySpan
.
List i
Thanks for all the comments explaining that there's no actual way to do it and how exposing the internal Array inside List could lead to bad behaviour and a broken span.
I ended up refactoring my code not to use a list and just produce spans in the first place.
void Consume(ReadOnlySpan buffer)
// ...
var buffer = new T[512];
int itemCount = ProduceListOfItems(buffer); // produce now writes into the buffer
Consume(new ReadOnlySpan(buffer, 0, itemCount);
I'm chosing to make the explicit tradeoff of over-allocating the buffer once to avoid making an extra copy later on.
I can do this in my specific case because I know there will a maximum upper bound on the item count, and over-allocating slightly isn't a big deal, however there doesn't appear to be a generalisation here, nor would one ever get added as it would be dangerous.
As always, software performance is the art of making (hopefully favorable) trade-offs.