tags:

views:

46

answers:

3

Hi, I am using C#. I have an array of size 10. I want to pass it to a function, but only from the second element. In C, this is how I would implement it

myfunc( myarray + 1 )

Effectively I am virtually shifting the array / deleting the first element.

How do I implement this in C# ?

+1  A: 

You could pass an index to the function also, and only access the array beginning at that index.

Justin Ethier
+4  A: 

If you're using .NET 3.5, the easiest is to use Skip(1) then convert back to an array.

myFunc(myArray.Skip(1).ToArray());

If performance is an issue then you will either need to construct a new array manually or change your function to accept an index parameter.

Mark Byers
Great, that works. I cant modify the function because it is part of another library and performance is not an issue.Thanks!!
UKM
+1 I was going to suggest Array.CopyTo(newArray, 1),but the extension method approach is easier to understand, perhaps with some negligible? performance cost.
Si
Now there are two ways. Thanks again.
UKM
+4  A: 

There are four options here:

  1. Pass in an index, and use that in your function
  2. Make your function use IEnumerable<T> instead of an array (T[]), then use myArray.Skip(1).
  3. Use skip, but convert back to an array. This copies the array elements, however.
  4. Use an ArraySegment<T> instead of an array for your function.

This really depends on whether you have control over the usage within your myfunc function. If that function must accept an array, and you can't pass an index, you're going to be stuck creating a copy of the array.

Reed Copsey