#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

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

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

  1. Bruce Lipp says:

    Most concise explanation I could find. Thank you.

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 )

Google+ photo

You are commenting using your Google+ 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: