C# array parameter reference -


this question has answer here:

i have c# code follows:

int[] = new int[] {1, 2, 3}; fun(a); // @ point still says 1, 2, 3.  void fun(int[] a) {    int[] b = new int[] {4, 5, 6};    = b; } 

i thought arrays passed reference in c#. shouldn't after calling fun() reflect 4, 5, 6?

the array passed a reference, can see doing a[0] = 7; inside method.

that reference (held outer variable a), passed value function. reference copied , new variable created , passed function. variable outside function not affected reassignment parameter variable a inside function.

to update original variable need use ref keyword parameter inside function represents same object outside of function.

int[] = new int[] {1, 2, 3}; fun2(a); // @ point says 7, 2, 3. fun(ref a); // @ point says 4, 5, 6.  void fun2(int[] a) {    a[0] = 7; }  void fun(ref int[] a) {    int[] b = new int[] {4, 5, 6};    = b; } 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -