#826 – Deep Copies

When making a copy of an object, you can either make a shallow copy or a deep copy.  As opposed to a shallow copy, a deep copy is one in which a copy is made not only of the top-level object, but of all the objects referenced by the original object.

During the copy process, whenever a reference to a child object is encountered, a new instance (or deep copy) of the child object is made.

For example, if a Dog object contains a reference to a DogCollar object and we make a deep copy, we get the following:

826-001

When doing a deep copy, a deep copy is typically made of all child objects in the object hierarchy.  For example, if the DogCollar instance had in turn referred to another object, a copy would have been made of that object.

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

6 Responses to #826 – Deep Copies

  1. if a object has nested children, to do deep copy, we need to take care of to the leaf node of it.. any patterns should be used or any industry standard way of doing, other than copy constructor or implement IClone() ? appreciate your help!

  2. dotnetchris says:

    Well this was a rather worthless article. Talks about what a deep copy obviously is, and then completely ignores how ridiculously complicated it is to get deep copies in .NET

  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#

  5. Pingback: #830 – The Problem with ICloneable | 2,000 Things You Should Know About C#

  6. Yann Duran says:

    Hi Sean,

    Hmm, this isn’t what I understood a “deep copy” to be. If you create new objects to be assigned to the reference type properties, unless you set all of the new object’s values to be the same as the original referenced object, then it’s not really a “copy” of the original object. Then you have to walk down the relationship tree, doing the same thing for any child objects. This is what makes a “deep copy” so hard to do.

    Of course I could be wrong?

Leave a comment