#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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: