#144 – Using Serialization to Implement Deep Copying

One alternative to using the ICloneable interface to support making a deep copy for a custom type is to use serialization.

This method will work only if the class to be copied, as well as all classes referenced by it (directly or indirectly), are serializable.

For example, if we have a Person class that has some value-typed members, but also a reference to an instance of the Address class, both the Person and Address classes have to be serializable in order to use this technique.

Here’s a generic method that makes a deep copy using serialization, serializing the object into a stream and then deserializing into a new object.

        public static T DeepCopy<T>(T obj)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                stream.Position = 0;

                return (T)formatter.Deserialize(stream);
            }
        }

Using this method to deep copy a Person:

            Person bronteClone = DeepCopy<Person>(emily);
Advertisements

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

4 Responses to #144 – Using Serialization to Implement Deep Copying

  1. Pingback: #266 – You Can’t Prevent a Method from Changing the Contents of Reference Types « 2,000 Things You Should Know About C#

  2. Beni says:

    the Class must marked as Serializable ,otherwise will not work

    • Sean says:

      Yes, see my comment in the post: “This method will work only if the class to be copied, as well as all classes referenced by it (directly or indirectly), are serializable”.

  3. bukan iJam says:

    Thank you. Very useful.

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: