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);
}
...
}
Related articles
Related discussion
-
Problem after strong naming an assembly
by rinkurathor1 (0 replies)
-
VB.net class to connect to sql database
by senol01 (2 replies)
-
ASP.NET Patterns every developer should know
by konikula (3 replies)
-
String was not recognized as a valid DateTime.
by buvanasubi (22 replies)
-
help me to get simple requirement
by Slicksim (1 replies)
Related podcasts
-
Looking into the C# Crystal Ball with Charlie Calvert and Bill Wagner
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...
Events coming up
-
Dec
6
Developing AJAX Web Applications with Castle Monorail
London, United Kingdom
Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!
This thread is for discussions of Clone an object in .NET.