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