#139 – Using the Array.Clone Method to Make a Shallow Copy of an Array

You can use the Clone method to copy all of an array’s elements to a new array.  The arrays’ elements must be of the same type.  Each element of the source array is copied to the destination array.

If the arrays contain a value type, you can change values in the destination array after copying without impacting values in the source array.

But if the arrays contain a reference type, the references to the objects are copied, so the destination array will point to the same objects as the source array.  A change in any object will therefore be seen by both arrays. This is known as a shallow copy.

            Person[] folks1 = new Person[2];
            folks1[0] = new Person("Bronte", "Emily");
            folks1[1] = new Person("Bronte", "Charlotte");

            // Copy the folks1 array
            Person[] folks2 = (Person[])folks1.Clone();

            // Change name of person in folks1
            folks1[1].FirstName = "Elvis";

            // Note that object in folks2 has also changed
            Console.WriteLine(folks2[1].FirstName);     // Elvis
Advertisements