.Net and Deep Copy
Some time ago I had to clone objects and .Net's shallow copy proved to be insufficient – it was necessary to use deep copy. No good tools are provided by .Net itself. If required, the object to be cloned must conform to the ICloneable interface and the Clone() method can be defined for the object. As the classes were not very numerous, but relatively bulky and complicated, there was no point in writing a Clone() method for all of them. I needed something else.
With the help of Google I found a very smart method for performing deep copy. Its performance may not be exceptional but it does its work nicely. The idea of the method is simple – first the object has to be serialised and then deserialised. Serialisation loses the relation between the specific instance of the object and the object data left to us. On deserialisation a new object identical to the old one is created based on these data, but now we are dealing with a different instance.
public object DeepCopy(object obj)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
object retval;
ms.Seek(0, SeekOrigin.Begin);
retval = bf.Deserialize(ms);
ms.Close();
return retval;
}
NB! This method can be used to deep copy only classes marked as serialisable. If there are problems with the events of the objects to be deserialised, you can find a solution from Rockford Lhotka's blog posting .NET 2.0 solution to serialization of objects that raise events. If the security level of the appropriate IIS application is not set to Full (internal), this method can generate errors in Windows Vista. If someone knows a solution to this problem, please don’t hesitate to inform me.
NB! PLEASE READ GREG'S COMMENT ABOUT THIS SOLUTION!!!