Jo Smo Jo Smo - 12 days ago 7
C# Question

How can a method without the out or ref change a variable outside itself? C#

How is it possible to change the values of an array

a
from the inside of
SumElemtnts
method? Is it because it's a static method? Because the method returns only the variable
sum
and there is no ref or out.

class Program
{
public static int SumElements(int[] a)
{
int[] a2 = a;
int sum = 0;
for (int i = 0; i < 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[] a = { 1, 2, 3 };
int sum = SumElements(a);

Console.Write("Sum = " + sum + ", ");
for (int i = 0; i < a.Length; i++)
{
Console.Write(a[i] + " ");
}
}
}


The result is:

Sum = 60, 10 60 30

Answer

An array is a reference type.

You're not passing in a copy of the array, you're passing in a reference to it.

Here's a smaller LINQPad program that demonstrates:

void Main()
{
    var a = new[] { 1, 2, 3 };
    Test(a);
    a.Dump();
}

public static void Test(int[] arr)
{
    arr[1] = 15;
}

Output:

1
15
3

Longer description: When you pass a value to a method in C#, it's "pass by value" as default, meaning that you're passing in a copy of the value, not the actual variable itself.

In this case you're passing in a copy of the reference, but the reference is referencing an array.

Thus the method has its own reference to the array, but it's still working with the same array as the code "on the outside".

Comments