Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#, get a sub-part of array without copying the data (like having C pointers)

I have a byte array with data like this (managed code)

byte[] test = {0xA,0xB,0xC,0xD}; // data is much longer...

If I explicit do like this, LINQ will create a copy from original array.

var test2 = test.Skip(1).Take(2).ToArray();

and I need a part of it, but without creating a copy as new array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Inspired by this,
Get a Array subset without copying like in C with pointers

var test2 = test.Skip(1).Take(2);

it works, but the result is IEnumerable and I need a pure byte[].

So basically the goal is to have a real chunk of original array (not a copy of chunk) and if I modify a element, to be reflected in chunk too (like having pointers in C)

Is it possible to convert IEnumerable to byte[] without copy?
Is it possible to do it otherwise (no LINQ)?

Thank you in advance!

>Solution :

It seems that you are looking for Span or Memory<byte>:

byte[] test = { 0xA, 0xB, 0xC, 0xD };

// Span is some kind of c-like pointer to the array
// first  2 - skip 2 items
// second 2 - take 2 items
Span<byte> span = new Span<byte>(test, 2, 2);

// We modify the array item...
test[3] = 0xFF;

// ... and span reflects the modification 
// Note that we have skipped 2 items, that's why span[1], not span[3]
byte result = span[1]; // 0xFF
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading