简体   繁体   中英

Array memory c# (copied to new reference or using the same?)

So I couldn't seem to figure this out. In the following code:

int[] array1 = { 86, 66, 76, 92, 95, 88 };
int[] array2 = new int[6];
array2 = array1;

When array2 is "copying" the values of array1, is it creating new memory references or is it referencing the same memory index as the values in array1?

Arrays are reference types, therefore you are assigning the same reference.

Array types are reference types derived from the abstract base type Array .

If you want to create a deep copy, you can use Array.Copy :

int[] array1 = { 86, 66, 76, 92, 95, 88 };
int[] array2 = new int[array1.Length];
Array.Copy(array1, array2, array1.Length);

Arrays are of reference type. You can easily check this yourself

array2[1] = 2;
Console.WriteLine(array1[1]); // will print out 2

When you change one you change the other because both point to (reference) the same memory location.

It is referencing the same array. So if you change a value in array1 it will also be changed in array2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM