Title: Clone serializable objects in C#
If a class is serializable, then you can create a deep clone of an object from that class by serializing it and the deserializing it. This example uses the following code to define a generic extension method that clones objects from any serializable class.
// Return a deep clone of an object of type T.
public static T DeepClone<T>(this T obj)
using (MemoryStream memory_stream = new MemoryStream())
// Serialize the object into the memory stream.
BinaryFormatter formatter = new BinaryFormatter();
// Rewind the stream and use it to create a new object.
memory_stream.Position = 0;
The code creates a BinaryFormatter and uses it to serialize the object into a memory stream. It then uses the formatter to deserialize the stream into a new object.
Using this extension method is simple. The following code shows how the example program uses it to make a deep clone of the object named person1.
person3 = person1.DeepClone();
For this to work, the class must be marked as serializable. The clone also only includes members of the class that are serializable. For example, if some of the class's properties are marked with the XmlIgnore attribute, then they won't be serialized or deserialized so the clone won't get the original object's values for those properties.
This example serializes a Person object. The following code shows the Person class's declaration.
class Person : ICloneable
The Person class has an Address property that is of the StreetAddress class. That class is also marked serializable so the DeepClone method can copy its value into the new Person object.
Download the example to experiment with it and to see additional details.