Cloning an Object
Posted by Kash Farooq on June 15, 2012
I thought I’d post this code as I frequently find myself needing it on various projects.
Making a deep copy clone of an object:
public static T CloneObject<T>(T objectToClone) { using (var memoryStream = new MemoryStream()) { var xmlSerializer = new XmlSerializer(typeof (T)); xmlSerializer.Serialize(memoryStream, objectToClone); memoryStream.Position = 0; return (T) xmlSerializer.Deserialize(memoryStream); } }
Basically, serialize an object to memory and then deserialize it into a completely different new object, breaking the memory reference.
Sorry, the comment form is closed at this time.