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

Jon Skeet
people
quotationmark

You're not changing the value of the variable within SumElements - that still refers to the same array that it did before. Note how there's no assignment to a within the SumElements method.

Instead, you're changing the contents of the array. That change is visible within Main, because that still has a reference to the array as well.

Think of a variable as being like a piece of paper. In Main, you have a variable called a, which contains a reference - a way of getting to the array. That's like having a piece of paper with a street address on. That's the street address of a house - analogous to the array object.

You're copying that value (the street address) and using it as the value of a in SumElements. The two pieces of paper are separate - you could scribble over the one in SumElements and that wouldn't change the piece of paper in Main - but they start off with the same street address. SumElements is then going to that street address, and painting one of the windows. When Main then goes to the same street address, it sees the painted window as well... because there's only one house (the array object) even though there were two pieces of paper with the same street address written on them.

See my articles on parameter passing and reference types and value types for more details.

people

See more on this question at Stackoverflow