Skip an array to work with a specific index in C # .Net

I am new to C # (previously worked in C ++), I used to pass an array to work with a 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 * ? *

+5
source share
5 answers

Since Array is Enumerable, you can use the LINQ functionSkip .

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

int[] myArray = { 0, 1, 2, 3, 4, 5, 6 }
MyFunc( myArray.Skip(2) );
+5
source

The linq version is my preferred. However, this will prove to be very ineffective.

You could do

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

and pass mySlice to a function

0
source

.NET System.ArraySegment<T>, .

But I never saw this structure used in the code, with good reasons: it does not work. It is noteworthy that it does not implement any interfaces, such as IEnumerable<T>. Therefore, the best option is a Linq (= using Skip) solution .

0
source

Probably the easiest way to do this:

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

And call it that way:

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

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

0
source
public void MyFunc(ref int[] arr)
{
    // Do something
}

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

For more details see ref here !

-2
source

All Articles