#142 – Implement ICloneable All the Way Down for Deep Copies

If you want to use the ICloneable.Clone method of a class to make a deep copy, you class must be implemented so that Clone provides a deep copy.  It’s up to the author of a class whether the Clone method makes a shallow or a deep copy.

If you want Clone to support deep copies and you are authoring the class, you can do one of two things:

  • If your class’ members are all value types, just use MemberwiseClone
  • Clone your object and then make a deep copy of any objects that it references

You can use Clone as a deep copy mechanism all the way down the object tree only if you are the author of each class and can implement deep copy semantics, or if you know that the objects your object references have a mechanism for making deep copies.

Advertisements