Deep copy, shallow copy and IClonable interface.

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

How to create deep copy?

You can use the below code to make a deep copy of the list or any other object supporting serialization:

public static class GenericCopier<T>
    public static T DeepCopy(object objectToCopy)
        using (MemoryStream memoryStream = new MemoryStream())
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, objectToCopy);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return (T) binaryFormatter.Deserialize(memoryStream);

Your class MUST be marked as [Serializable] in order for this to work.
For example, to create copy on List we do something like this:

List<int> deepCopiedList = GenericCopier<List<int>>.DeepCopy(originalList);


Microsoft recommends against implementing ICloneable because there’s no clear indication from the interface whether your Clone method performs a “deep” or “shallow” clone.

“Because callers of Clone cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable not be implemented in public APIs.”

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this