A way to access a subset of an array?

I am trying to figure out if there is a way to do something in C #, which is pretty easy to do in C ++. In particular, if I have an array of data, I can create a pointer to this data for more convenient access to the subsection.

For example, if I have:

unsigned char buffer[1000]; 

and I determine that there is a line at positions from 102 to 110 inside this array, that I need to manipulate a lot, I can do this:

 unsigned char *strPtr = &buffer[102]; char firstChar = strPtr[0]; 

This eliminates the need for me to add β€œ102” to each array index in subsequent operations.

While I learn about the possibility of unsafe situations when you are doing something like this, I wonder if there is a moral equivalent in C # that would allow me to create a new link to a subset of an existing array.

Sort of:

 byte [8] newArray = &buffer[102]; 

This example does not actually work, or I would not publish it, but I think it gets an idea of ​​what I want to accomplish.

+5
source share
1 answer

Here's an ArraySegment<T> class that can be used as a wrapper to access segments of an array. Just specify the array, offset, and segment length, and you can use it as if it were an actual array. You will get border checks and other subtleties of using arrays.

 var buffer = new byte[1000]; var newArray = new ArraySegment<byte>(buffer, 102, 8) as IList<byte> // we have an "array" of byte[8] var firstChar = newArray[0]; 

However, there is a suggestion to introduce a slice of the array. Like ArraySegment, slices allow you to create representations in arrays (without creating copies) and can be used instead of real arrays. Hope it turns it into the (closest) version of C #.

+4
source

Source: https://habr.com/ru/post/1241340/


All Articles