Deep Copy

Making copies of objects is harder than it appears. You might think that you just need to make a new instance of a class and copy the instance variables over. This is called a shallow copy. The problem with this approach is that both objects will point to the same instance of their parts. If one part is a collection, for example, that collection becomes shared and adding to the collection from one object will appear to affect the copy. A second approach is called a custom copy. After making the copy, you explicitly make copies of some of its instance variables. This may work better but it can't copy objects that point to each other or objects that have to point to a shared object. You can do a deep copy by passing an Identity Dictionary to the copy method to store the mapping from original objects to copies. This does a good job with loops and shared objects. It may, however, copy too much. You run the risk of copying things you don't want copied. Finally, there's a partial copy which is used for undo mechanisms. It makes a shallow copy of each object you are about to change then allows you to change the original. To undo, you restore the shallow copies back to the original objects.

In the end, making copies can be tough to get right, so it's a good idea to understand your options and choose the best technique for your application.

Download