Search code examples
c#arrays.netclone

(Array.Clone) Shallow Copy vs Deep Copy of an Array


  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?


Solution

  • A Shallow Copy of an Array is not the same as a copy of an array:

    • Copying an array, copies the reference to the array to a new variable. Both variables will be pointing to the same values.
    • The 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.
      If the elements of the array are of a reference type, the new array will contain copies of the original references. So the first elements of both array would contain the same reference to an object.

    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.