#143 – An Example of Implementing ICloneable for Deep Copies

Here’s an example of implementing ICloneable in two custom classes so that you can use the Clone method to do a deep copy.

To do a deep copy of the Person class, we need to copy its members that are value types and then create a new instance of Address by calling its Clone method.

        public class Person : ICloneable
        {
            public string LastName { get; set; }
            public string FirstName { get; set; }
            public Address PersonAddress { get; set; }

            public object Clone()
            {
                Person newPerson = (Person)this.MemberwiseClone();
                newPerson.PersonAddress = (Address)this.PersonAddress.Clone();

                return newPerson;
            }
        }

The Address class uses MemberwiseClone to make a copy of itself.

        public class Address : ICloneable
        {
            public int HouseNumber { get; set; }
            public string StreetName { get; set; }

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

Cloning a Person:

            Person herClone = (Person)emilyBronte.Clone();

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #143 – An Example of Implementing ICloneable for Deep Copies

  1. Dipmalya Majumder says:

    Great example Sean.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers