+ 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

9th Sep 2021, 9:18 AM
Tim
Tim - avatar
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; }
9th Sep 2021, 9:20 AM
AĶ¢J
AĶ¢J - avatar
+ 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);
9th Sep 2021, 1:54 PM
Agnes Ahlberg
Agnes Ahlberg - avatar
+ 2
Agnes Ahlberg Arrays are value type?
9th Sep 2021, 6:18 PM
Tim
Tim - avatar
+ 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/
9th Sep 2021, 6:46 PM
AĶ¢J
AĶ¢J - avatar
+ 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 šŸ¤—šŸ’•
9th Sep 2021, 8:08 PM
Agnes Ahlberg
Agnes Ahlberg - avatar
+ 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
9th Sep 2021, 8:15 PM
Tim
Tim - avatar