5

I am new to C# (previously working on C++), I used to pass array to function with specific index. Here is the code in C++,

void MyFunc(int* arr) { /*Do something*/ }

//In other function
int myArray[10];
MyFunc(&myArray[2]);

Can I do something like this in C# .Net* ?*

Viktor Apoyan
  • 10,655
  • 22
  • 85
  • 147
vrajs5
  • 4,066
  • 1
  • 27
  • 44

5 Answers5

5

As Array is Enumerable, you can make use of LINQ function Skip.

void MyFunc( int[] array ){ /*Do something*/ }

int[] myArray = { 0, 1, 2, 3, 4, 5, 6 }
MyFunc( myArray.Skip(2) );
Draco Ater
  • 20,820
  • 8
  • 62
  • 86
  • 1
    It worked I jst have to add ToArray after skip statement. myArray.Skip(1).ToArray() – vrajs5 Apr 26 '11 at 10:07
  • 2
    @vrajs5: think about making MyFunc accepting IEnumerable, if MyFunc processes the array one after one element anyway. ToArray() creates a copy of myArray. – Ozan Apr 26 '11 at 10:29
  • Ah, that's cool, I've never seen the Linq Skip function before. Personally though, that seems so inefficient i think i would just change MyFunc to internally skip first 2 elements, or even add a new param for element number for MyFunc to start at... I guess it depends... – jonchicoine Apr 26 '11 at 15:57
0

The linq version is my preferred one. However it will prove to be very very inefficient.

You could do

int myArray[10];
int mySlice[8];
Array.Copy(myArray, 2, mySlice, 0);

and pass mySlice to the function

sehe
  • 374,641
  • 47
  • 450
  • 633
0

.NET has the System.ArraySegment<T> structure which addresses this exact use-case.

But I’ve never actually seen this structure used in code, with good reasons: it doesn’t work. Notably, it doesn’t implement any interfaces such as IEnumerable<T>. The Linq solution (= using Skip) is consequently the best alternative.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

Probably the most simple way to do this is:

public void MyFunction(ref int[] data,int index)
    {
        data[index]=10;
    }

And call it by this way:

int[] array= { 1, 2, 3, 4, 5 };
Myfunction(ref array,2);
foreach(int num in array)
    Console.WriteLine(num);

This will print 1,2,10,4,5

tommy
  • 1,006
  • 1
  • 11
  • 13
-2
public void MyFunc(ref int[] arr)
{
    // Do something
}

int[] myArray = .... ;
MyFunc(ref myArray);

See here for more information on ref!

Jaapjan
  • 3,365
  • 21
  • 25
  • 2
    He wants to pass part of an array, no the whole thing. That's completely different. – alex Apr 26 '11 at 09:46