The array is passed by a reference, you can see this by doing A[0] = 7;
from inside another method.
That reference (held by the outer variable A
), however is passed by value to the function. The reference is copied and a new variable is created and passed to the function. The variable outside the function is not affected by the reassignment to the parameter variable A
inside the function.
To update the original variable you need to use the ref
keyword so the parameter inside the function represents the same object as outside of the function.
int[] A = new int[] {1, 2, 3};
fun2(A);
// A at this point says 7, 2, 3.
fun(ref A);
// A at this point says 4, 5, 6.
void fun2(int[] a)
{
a[0] = 7;
}
void fun(ref int[] a)
{
int[] B = new int[] {4, 5, 6};
a = B;
}