#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

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

4 Responses to #141 – Implementing ICloneable for a Custom Type

  1. Veera says:

    But.. string is not a value type!!!

  2. Sean says:

    Right, string isn’t a value type. But it IS immutable. And a new string is created whenever you assign to a string property/field. Which means that if you create a clone of an object that contains strings and then change those strings in one object, you won’t see the changes in the second object. So, for purposes of MemberwiseClone, you can treat the strings as value types.

  3. Pingback: #828 – Implementing Both a Copy Constructor and ICloneable | 2,000 Things You Should Know About C#

  4. Pingback: #829 – Add Comments to Indicate Shallow vs. Deep Copying | 2,000 Things You Should Know About C#

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: