Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array starting with offset

Tags:

arrays

c#

I am using C#, and it's rather annoying that I can't send an array starting from a certain point like in C++.

suppose this code:

int[] array = new int[32];
foobar (array + 4); //send array starting from the 4th place.

this is a weird syntax for C# because we don't have any usable pointers, but surely there's a way to do it? There's .Skip(), but I think it produces a new array, which is something I do not like.

What are my options?

like image 277
Nefzen Avatar asked Jun 28 '09 22:06

Nefzen


2 Answers

You might want to pass it as an IEnumerable<int> rather than as an array. You can then use skip and it will simply move the iterator over the number of elements skipped. Used this way, you won't have to use ToArray() and create a copy of the portion of the array in question. Of course, IEnumerable may not be appropriate for what you want to do, but that's difficult to tell from your question.

public void FooBar( IEnumerable<int> bar )
{
  ...
}

int[] array = new int[32];
FooBar( array.Skip(4) );
like image 183
tvanfosson Avatar answered Oct 19 '22 20:10

tvanfosson


.NET has the System.ArraySegment wrapper – unfortunately, it's completely useless since it doesn't implement IEnumerable.

like image 22
Konrad Rudolph Avatar answered Oct 19 '22 21:10

Konrad Rudolph