Span - access to original value

739 Views Asked by At

I wish to obtain the original value a Span represents. Take the following code for example, how would I, in DoWork, gain access to the original byte array without creating a copy of it?

static void Main()
{
    var data = new byte[0x100];
    DoWork(new Span<byte>(data));
}

private void DoWork(Span<byte> Data)
{
    //var data = Data.ToArray(); Unsuitable; creates a copy
    //var data = (byte[])Data; Unsuitable; doesn't work
    //MemoryMarshal. Something in here may work, but unsure
    //MemoryExtensions. Something in here may work, but unsure
}

I found 2 static classes with helper methods (shown above) that may help, but I am unsure as to what is the best way to do this without making things slower than just making a copy.

1

There are 1 best solutions below

1
ClarHandsome On

According to the Span Document:

Because it is a stack-only type, Span is unsuitable for many scenarios that require storing references to buffers on the heap. This is true, for example, of routines that make asynchrous method calls. For such scenarios, you can use the complimentary System.Memory and System.ReadOnlyMemory types.

So maybe to your need, you don't have to use a Span:

static void Main()
{
    var data = new byte[0x100];
    DoWork(data);
}
private void DoWork(byte[] data)
{
    // data array is by reference.
}