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* ?*

1
  • I don't think it's possible to do such a thing. Commented Apr 26, 2011 at 9:47

5 Answers 5

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) );
Sign up to request clarification or add additional context in comments.

3 Comments

It worked I jst have to add ToArray after skip statement. myArray.Skip(1).ToArray()
@vrajs5: think about making MyFunc accepting IEnumerable<int>, if MyFunc processes the array one after one element anyway. ToArray() creates a copy of myArray.
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...
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

Comments

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.

Comments

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

Comments

-2
public void MyFunc(ref int[] arr)
{
    // Do something
}

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

See here for more information on ref!

1 Comment

He wants to pass part of an array, no the whole thing. That's completely different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.