Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a part of an array in C#

I have got the array containing some data, say, a header and a real data. I need to pass the data contained in the array to a method, but I definitely want to avoid copying it to another array.

I thought of something like ArraySegment, but it seems not to work in my case (or maybe I'm wrong?).

So, how to pass a part of an array to a method, as it was an array itself?

Thank you for your replies!

Cheers

like image 694
Jamie Avatar asked Aug 30 '10 19:08

Jamie


People also ask

How do you reference an element in an array?

The entire array can be referenced using just the array name, with no index. This is useful for assigning the same value to every element or clearing all the values in the array. The syntax is dim array([lbound to] ubound).

Can you reference an array in C?

An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.

Is it possible to pass a portion of an array to a function?

You can't pass arrays as function arguments in C. Instead, you can pass the address of the initial element and the size as separate arguments.

Can you slice array in C?

Array-slicing is supported in the print and display commands for C, C++, and Fortran.


2 Answers

Skip and Take:

var subArray = array.Skip(5).Take(10);
like image 64
Darin Dimitrov Avatar answered Oct 02 '22 17:10

Darin Dimitrov


If you want to stick to just basic arrays (ie int [] numbers), then the most efficient way is to have your functions take the offset/count directly.

There are lots of IO functions that do something similar:

readData(data, 0, 4);

string readData(byte [] buffer, int offset, int length)

The other option is to use IEnumberable< T > and use skip/take

readData(data.Skip(0).Take(4));

string readData(IEnumerable<byte> buffer)

It's important to remember that in c# you aren't dealing with pointers, you are dealing with objects.

like image 37
Alan Jackson Avatar answered Oct 02 '22 15:10

Alan Jackson