How can I use MemoryStream to create a deep clone of a serializable object ?

This can be done as follows.

[C#]

public static class SerializationUtil
{
   static public T Clone(T source)
   {
      Debug.Assert(typeof(T).IsSerializable);

      IGenericFormatter formatter = new GenericBinaryFormatter(); 
      Stream stream = new MemoryStream(); 
      formatter.Serialize(stream,source);
      stream.Seek(0,SeekOrigin.Begin);

      T clone = formatter.Deserialize(stream);
      stream.Close(); 
      return clone;
   }
//Rest of SerializationUtil
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.