Library code snippets

Deep clone an object in .NET

There are two types of object cloning; deep and shallow.

A shallow clone creates a new instance of the same type as the original object, with all its value-typed fields copied. However, the reference type fields still point to the original objects; and so the "new" object and the original reference to the same object. On the other hand, a deep clone of an object contains a full copy of everything directly or indirectly referenced by the object - and so you get a "true" copy.

One of the easiest ways to deep-copy an object is to serialize the object into memory and de-serialize it again - although this does require the object graph to be serializable. Here's a handy code snippet to do this:

public static object CloneObject(object obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter(null,
new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, obj);
memStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memStream);
}
}

You could then implement the ICloneable interface on your object like so:

public class MyObject  : ICloneable {
public object Clone()
{
return ObjectUtility.CloneObject(this);
}
...
}

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of Clone an object in .NET.

  2. 24 Jun 2009 at 11:15

    Uou can learn more on serialization / deserealization diggin into the code:

    http://plugins.codeplex.com

  3. 21 Jul 2009 at 02:46
  4. 22 Aug 2009 at 04:09

    it seems you have used the IFormatter class for serialization instead of Xml Serialization, great code specially in a time where sell own software sites are very popular

  5. 12 Aug 2010 at 07:34

    You could then implement the ICloneable interface on your object like so:

    public class MyObject : ICloneable { public object Clone() { return ObjectUtility.CloneObject(this); } ... }

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Related discussion

Related podcasts

  • Deep Fried Bytes: Looking into the C# Crystal Ball with Charlie Calvert and Bill Wagner

    Published 1 year ago, running time 0h31m

    One of the most exciting announcements from PDC was the news about C# 4.0 and Visual Studio 2010. With all the excitement and discussion throughout the event about these new developer tools, we reached out to two experts in the fields. Charlie Calvert and Bill Wagner sat down with Keith and Woody... csharp, microsoft, visual studio, developer

Related jobs

Events coming up

Want to stay in touch with what's going on? Follow us on twitter or Facebook!