Thursday, May 9, 2013

Cloning an object using serialization

This technique is useful when an object has several nested objects.


  1. Serialize the original object to XML
  2. Deserialize the XML back to a new object
  3. Cast the new (cloned) object to the type of the original object
T original;
string xmlCloned;
XmlSerializer xs = new XmlSerializer(original.GetType());
using (StringWriter writer = new StringWriter())
{
     xs.Serialize(writer, original);
     xmlCloned= writer.ToString();
}
StringReader sr = new StringReader(xmlCloned);
xs = new XmlSerializer(original.GetType());
T cloned = (T)xs.Deserialize(sr);