+ 1
Confused by how arrays work in C#
In the Modify method, the first line is able to modify the array but not the second, I wonder what's going on under the hood Any answer is appreciated š https://code.sololearn.com/cjQD7D8p2F25/?ref=app
6 Answers
+ 6
Nick
You are creating new array but still the reference of passing array is same. That's why assigning 4 at 0th index.
You have printed the value of reference array not second array.
To print second arr return that arr then assign to numbers and then print.
Like this:
static void Main(string[] args)
{
int[] numbers = new int[3];
numbers = Modify(numbers);
foreach (int i in numbers)
Console.WriteLine(i);
}
static int[] Modify(int[] arr)
{
arr[0] = 4;
arr = new int[] { 1, 2, 3 };
return arr;
}
+ 3
An array is a value type š¤ [edit: turned out they aren't, I must have mixed something up š] Only a copy to the array is visible in the method, it is like "arr" is a different variable. Giving it a new array does that only to "arr", not "numbers".
If you want "numbers" to change, you can pass as reference:
static void Modify(ref int[] arr)
{
arr[0] = 4;
arr = new int[] { 1, 2, 3 };
}
And call it with ref:
Modify(ref numbers);
+ 2
Agnes Ahlberg
Arrays are value type?
+ 2
Nick
Arrays are reference type. I don't know why she said value type.
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
+ 2
Oops š
Yes, you are right, they are reference types š I thought that I read "value type" somewhere š¤ Sorry š¤
Then why does it work using "ref" ? I think that it is still correct that "arr" is a different variable. And that is why the assignment does not work š
Thank you for pointing out my mistake š¤š
+ 1
Agnes Ahlberg, don't worry, we're here to learn, don't be afraid to make mistakes
And I believe ref is pointing to the address of arr, which is probably why numbers are able to be given a new set of values