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
-
Socket Programming in C# - Part 1
by graumanoz (23 replies)
-
Creating a Windows Service in VB.NET
by Templario55 (107 replies)
-
C# Windows Application Problem in Dynamically generated control
by BAmoozad (1 replies)
-
Using ADO.NET with SQL Server
by Manjot Bawa (23 replies)
-
High-Performance .NET Application Development & Architecture
by Manjot Bawa (0 replies)
Related podcasts
-
A Practical Look at Silverlight 2 Part 1
Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...
Events coming up
-
Nov
18
15 Minutes of Fame
Dresher, United States
This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.
Uou can learn more on serialization / deserealization diggin into the code:
http://plugins.codeplex.com
!--removed tag-->This thread is for discussions of Clone an object in .NET.