#140 – Making a Deep Copy of an Array Using an Object’s Clone Method

When you use the Array.Clone method of an array to make a copy of an array that contains instances of a reference type, you get a shallow copy–the new array references the same underlying objects as the original array.

A deep copy of an array is one in which you create a new copy of each element, so that the new array references different objects.

You can possibly make a deep copy if the element type has a Clone method.

            // Shallow copy of the array
            Person[] folks2 = (Person[])folks1.Clone();

            // Deep copy by calling Clone method on each element
            Person[] folks3 = new Person[folks1.Length];
            for (int i = 0; i < folks1.Length; i++)
                folks3[i] = (Person)folks1[i].Clone();

We’re now calling Clone on each element, rather than on the array itself.

This method doesn’t guarantee a deep copy, since there’s no guarantee that Person.Clone will give us a deep copy of Person.

Advertisements