Thursday, 4 March 2010

Deep cloning object in C#/.NET

I was asked recently to write a generic method for deep cloning of a complex object. The object contains references to other objects, collections, which contain references to many other objects and collections. The method was supposed to work on both platforms: .NET 3.5 (or higher) and Silverlight.

While googling I found a good post listing different approaches for cloning
C# Object Clone Wars

Last technique described in that blog points to Copyable Framework - generic framework for copying/cloning any objects using method extensions

The framework, written by HÃ¥vard Stranden addresses most of my requirements, except one: it does not work on Silverlight.

I came up with a simple method that serializes the original object and deserializes it to a cloned copy of it. It can be used as an extension or by implementing IClonable interface:

public static class ObjectExtensions
  public static T Clone<T>(this object original)
    T cloned;
    using (MemoryStream stream = new MemoryStream())
      DataContractSerializer serializer = new DataContractSerializer(typeof(T));
      serializer.WriteObject(stream, original);
      stream.Position = 0;
      cloned = (T)serializer.ReadObject(stream);
    return cloned;

* This source code was highlighted with Source Code Highlighter.
Post a Comment