#141 – Implementing ICloneable for a Custom Type

A type can choose to implement the ICloneable interface, which includes the single Clone method.  The intent of the Clone method is to create a copy of the object.

The simplest way to create a copy of the object is to call the Object.MemberwiseClone method.

        public class Person : ICloneable
        {
            public string LastName { get; set; }
            public string FirstName { get; set; }
            public Person(string lastname, string firstname)
            {
                LastName = lastname;
                FirstName = firstname;
            }

            public object Clone()
            {
                return this.MemberwiseClone();
            }
        }

If your intention is to make a deep copy and your type contains only members that are value types, this is sufficient.  However, if the type contains members that are reference types, you’ll have to do more in order to get a deep copy.

Advertisements

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