How can I copy from a ReadOnlySpan<T> to an Array<T>?

Viewed 1910

My class has a property public byte[] Location{get;} = new byte[30];

I want to be able to fill it from a ReadOnlySpan<byte> but I cannot find any API methods allowing this.

The closest I've found is:

var array = span.Slice(0,30).ToArray();
Array.Copy(array, Locations, 30);

But having to create a new array just to copy from it seems really ugly... one array creation and 2 copies are involved. I could make the property settable but it's not really the intended design.

Am i missing some obvious method?

1 Answers

You could use a Span<byte> to target your Location array, then use CopyTo for the copy:

var source = new ReadOnlySpan<byte>(Source).Slice(0, 30);
var target = new Span<byte>(Location, 0, 30); //Modify start & length as required

source.CopyTo(target);
Related