Reputation: 21
int[] myArray = {1, 2, 3, 4, 5};
Console.WriteLine(myArray[0]);
int[] localArray = (int[])myArray.Clone();
localArray[0] = 10;
Console.WriteLine(myArray[0]);
Console.WriteLine(localArray[0]);
The output of the following was:
1
1
10
As to my understanding, both myArray[0] and localArray[0] should point to the same integer, and if I change localArray[0] to 10, it should reflect upon myArray[0] as well. But as the output suggests they both point to different integers. What's going on here?
Upvotes: 1
Views: 3229
Reputation: 164
If elements are value type then "Shallow Copy" == "Deep Copy" (as "int' in this case). In case if elements are reference type then "A Shallow Copy of an Array is not the same as a copy of an array:" and below as wrote the @Johan Donne
Upvotes: 0
Reputation: 3285
A Shallow Copy of an Array is not the same as a copy of an array:
Clone
method creates a new, distinct array containing a copy of the elements of the original array. If those elements are value types (like in your case ìnt
) the new array will contain the same set of values as the original but stored in another location.See also: https://learn.microsoft.com/en-us/dotnet/api/system.array.clone?view=net-6.0
A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
Upvotes: 5