[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Clone serializable objects in C#

[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(); formatter.Serialize(memory_stream, obj); // Rewind the stream and use it to create a new object. memory_stream.Position = 0; return (T)formatter.Deserialize(memory_stream); } }

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.

[Serializable()] 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.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.