Reputation: 5890
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?
Upvotes: 3
Views: 359
Reputation: 384
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
Upvotes: 0
Reputation: 56769
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);
}
Upvotes: 6