using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Clifton.Tools.Data { public static class Cloner { /// <summary> /// Performs a deep clone by serializing the object, then deserializing it into a new object. /// The BinaryFormatter is used, so all classes in the object graph must be marked as serializable. /// </summary> public static T CloneObject<T>(T obj) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); ms.Position = 0; T newObj = (T)bf.Deserialize(ms); return newObj; } /// Performs a deep clone by serializing the object, then deserializing it into a new object. /// The XmlSerializer is used, so all properties must be appropriately attributed with XML /// serialization tags. public static T XmlCloneObject<T>(T obj) { XmlSerializer xs = new XmlSerializer(typeof(T)); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); xs.Serialize(sw, obj); sw.Close(); StringReader sr = new StringReader(sb.ToString()); T newObj = (T)xs.Deserialize(sr); sr.Close(); return newObj; } } }
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)