How does Array.Clone() handle copied references?

Hey everyone, I’ve got an issue relating to the inner workings of Array.Clone(). It is my understanding that Clone() makes a shallow copy of an array, meaning that the elements from one array are copied into a different array, with each element retaining a reference to the same space in memory.

If I were to write this:

//ClassA

GameObject[] arrayA = new GameObject[5];

// Call some method that inserts a GameObject into each index of arrayA.


//ClassB

GameObject[] arrayB = new GameObject[5];

arrayB = (GameObject[])ClassA.arrayA.Clone();

I would expect that since I performed a shallow copy of arrayA into arrayB, that if I then go and change some elements in arrayB, the changes would be reflected in arrayA. For instance, shouldn’t setting everything in arrayB to null set every element in arrayA to null as well? In my testing this does not happen. Are the elements in the two arrays not actually pointing to the same references?

A bit confused here…

You are in fact creating a shallow copy of the array. From the MSDN docs:

“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.”

What this means is that if you were to create two arrays of something like ints (values) or references to GameObjects and changed them then you would only change them for each individual array. If, on the other hand, you were to change the component properties of a GameObject in one of the arrays it would affect the GameObject that is referenced in the other array because they both point to the same object still.

No, cloning will use the same references initially, so they will have the same values but updating the value of one will not update the other, it’ll change the reference. Why are you using clone? What you’re looking for would work simply by setting one equal to the other.

string[] A = new string[] {"1", "2"};
string[] B = A;

B[0] = "100";

this will set both A[0] and B[0] = “100”;