6

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?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Did you find any other solutions for this task? – Oliver Jul 14 '20 at 12:21
  • 1
    Not so far - I'm leaving it to gain a bit more attention otherwise I'll accept your answer which seems at least a bit better than my approach :) – Mr. Boy Jul 14 '20 at 12:24

1 Answers1

14

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);
Oliver
  • 8,794
  • 2
  • 40
  • 60
  • 1
    Very nice, thank you. For me this is even (a bit) faster than `Buffer.BlockCopy()` (which in turn is just as fast as "unsafing" out to `memcpy`. Yes I benchmarked it 'cuz I had to know... :) YMMV – Maxim Paperno Feb 26 '22 at 08:48