Kash Farooq's software development blog

.NET Developer

Posts Tagged ‘Objects’

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.

Advertisements

Posted in .NET | Tagged: , , | Leave a Comment »