How to Deep Clone an Object Model

Posted: November 26, 2010 in Quick Tips
Tags: , ,

With the adoptation of ORM, it is becoming increasingly useful to be able to clone an object graph. This is particualry useful when using the Entity Framework on the POCO model.

This extension method attaches itself to the object class. We use binary serialization to serialize into a memory stream then back out to the target class, essentially making a perfect copy of the object.

This method will also copy any complex object and traverse the entire object graph.

 

public static T DeepClone(this T obj)
{
  using (var ms = new MemoryStream()) {
    var bf = new BinaryFormatter();
    bf.Serialize(ms, obj);
    ms.Position = 0;
    return (T)bf.Deserialize(ms);
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s