Can I create a new array reference that contains a subset of an existing array without copying the memory?

I am creating a file reader in C # and large amounts of data will be listed. I want to use the same buffer for each item that I read, and then pass the buffer for further processing by the client. The API would be cleaner if I could return the byte[] correct size, rather than the raw buffer and length.

Is it possible to do this in C # without copying the memory?

+4
source share
3 answers

You can use ArraySegment<T>

http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx

This allows you to specify the beginning and end of the segment that you want to transfer without copying any data.

+7
source

If you can change API parameter types, I think you could use ArraySegment .

+4
source

ArraySegment type is a general structure that allows us to store information about a range of arrays. It is useful for storing ranges of arrays. ArraySegment facilitates optimizations that reduce memory and heap allocation.

From MSDN;

The Array property returns the entire source array, not a copy of the array; therefore, changes made to the array returned by the array property are created in the original array.

Here is the DEMO .

+1
source

All Articles