Using Serialization as a general Deep Copy

I have a theory that I would like to run by everyone.  Assuming a class say TestClass is Serializable. Would the following function work in general to do a deep copy of that class?

public TestClass Copy()
{
  MemoryStream memoryStream = new MemoryStream();
  BinaryFormatter binaryFormatter = new BinaryFormatter();
  
  binaryFormatter.Serialize(memoryStream, this);
  memoryStream.Seek(0, SeekOrigin.Begin);

  return (TestClass)binaryFormatter.Deserialize(memoryStream);
}
I'm kind of new to this serialization stuff so if anyone can give me feed back about whether they think this would work or not I would appreciate it.

1 Comment

  • Well, first and foremost, all classes in the hierarchy must be serializable in this case. Beyond that, if you have any events on one of the classes in the hierarchy, Serialization will FAIL miserably.

Comments have been disabled for this content.