pass by reference - How can a method without the out or ref change a variable outside itself? C# -
this question has answer here:
how possible change values of array a
inside of sumelemtnts
method? because it's static method? because method returns variable sum
, there no ref or out.
class program { public static int sumelements(int[] a) { int[] a2 = a; int sum = 0; (int = 0; < a2.length; i++) { int temp = a2[i] * 10; a2[i] = temp; sum += temp; } a[a2.length - 2] = sum; return sum; } public static void main(string[] args) { int[] = { 1, 2, 3 }; int sum = sumelements(a); console.write("sum = " + sum + ", "); (int = 0; < a.length; i++) { console.write(a[i] + " "); } } }
the result is:
sum = 60, 10 60 30
an array reference type.
you're not passing in copy of array, you're passing in reference it.
here's smaller linqpad program demonstrates:
void main() { var = new[] { 1, 2, 3 }; test(a); a.dump(); } public static void test(int[] arr) { arr[1] = 15; }
output:
1 15 3
longer description: when pass value method in c#, it's "pass value" default, meaning you're passing in copy of value, not actual variable itself.
in case you're passing in copy of reference, reference referencing array.
thus method has own reference array, it's still working same array code "on outside".
Comments
Post a Comment