3

Is there any way can C# pass an array in function like C++?

In C++, we can pass the array plus offset and length very neat like below

void myFunction(int A[], int m) // m is length of A
{
    myFunction2(A+1, m - 1); 
}

Can C# do it too?

2 Answers 2

6

Sure. However you can't modify pointers, so you would need to pass the offset separately. Also, you don't need to pass around the length, because all C# Arrays have a .Length property to get the array size.

void MyFunction(int[] A, int offset)
{
    MyFunction2(A, offset + 1);
}
Sign up to request clarification or add additional context in comments.

4 Comments

You edited your answer, so I'll just keep the second part of my comment: in many cases, you can actually find the length of an array in C and C++ by using sizeof(array) / sizeof(array_type); you just have to be careful you aren't using a regular pointer instead of an array, because in that situation it will fail (in that it will just give you the size of the pointer) and you will have to pass in an actual length instead.
There is another situation that I want the above portion of A[], like A[0] ~ A[A.Length/2]. In C++ we can do MyFunction2(A, m/2 + 1). How can we do this in C#?
@DeshengLi: You would pass the effective length just the same in C#, e.g., void MyFunction(int[] A, int maxIndex)
So we have do myFunction2(int[] A, int aoffset, int amaxIndex)
0

In C# you aren't passing in the pointer to the array, you're passing in an array reference.

void myFunction(int[] array, int offset)
{
    myFunction(array, offset + 1);
}

This will effectively do the same thing. It's important to know that the length is unnecessary because the array itself is an object reference which carries around the length of the array. So your real length relative to your example can be obtained via array.Length - offset

Comments

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.