July 15, 2005

.Net Deep Copy or Cloning Using Serialization

Heres some code I developed to make a deep copy of an object using serialisation.
public class Cloner
{
      
  static public object _GenericDeepCopy(object target)
  {
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    // Serialize the object into the stream.
    bf.Serialize(ms, target);
    //Position streem pointer back to first byte.
    ms.Seek(0, SeekOrigin.Begin);
    // Deserialize into another object.
    object clone = bf.Deserialize(ms);
    // Release memory.
    ms.Close();
    return clone;
  }

  static public XXX _XXXDeepCopy(XXX dcLookUpTable)
  {
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    // Serialize the object into the stream.
    bf.Serialize(ms, dcLookUpTable);
    //Position streem pointer back to first byte.
    ms.Seek(0, SeekOrigin.Begin);
    // Deserialize into another object.
    XXX cloneObject = (XXX)bf.Deserialize(ms);
    // Release memory.
    ms.Close();
    return cloneObject;
  }
}

No comments: