Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to access subset of array?

Tags:

c#

I'm trying to figure out if there's a way to do something in C# that's fairly easy to do in C++. Specifically, if I have an array of data, I can create a pointer into that data to access a subsection more conveniently.

For example, if I have:

unsigned char buffer[1000];

and I determine that there's a string at positions 102 to 110 within that array that I need to manipulate a lot, I can do this:

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

This saves me from having to add "102" to each array index in subsequent operations.

While I recognize the possibility of unsafe situations when you do something like this, I'm wondering if there is a moral equivalent in C# that would let me create a new reference to a subset of an existing array.

Something like:

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

That example doesn't actually work or I wouldn't be posting this, but I think it gets the idea of what I want to accomplish across.

like image 703
Mike Fulton Avatar asked Jan 24 '16 02:01

Mike Fulton


1 Answers

There's the ArraySegment<T> class which can be used as a wrapper to access segments of an array. Just provide the array, an offset and the length of the segment and you could use it as if it were the actual array. You'll get bounds checking and other niceties 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];

There is a proposal however to introduce array slicing. As like the ArraySegment, slices allow you to create views into arrays (without making copies) and can be used in place of actual arrays. Hopefully it will make it into a (near) future C# version.

like image 110
Jeff Mercado Avatar answered Oct 11 '22 18:10

Jeff Mercado