Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Monday, April 06, 2009

Cloning in C#.NET.

We all know that objects are reference types. When we assign objects they will point to same location and any changes made will effect both the objects. In order to change the default behaviour...meaning in order to maintain two different copies of the objects we have two options.

Option 1: Shallow or Deep copying an object using Cloning

Implement the entity class from ICloneable interface and implement the Clone method as outlined.

Shadow Cloning: This cloning allows to copy an object with all the required members. But if the entity internally has objects we need to go for deep cloning.

public object Clone()


return this.MemberwiseClone();


Deep Cloning: This cloning allows the entity to be copied along with all the entities it internally holds. Suppose we need to clone a TestList which is list of Test entity.

First we need to clone each "Test" memberwise and apply deep cloning for TestList entity.

#region ICloneable Members

public object Clone()


TestList LobjTestList = new TestList();

foreach (Test LobjTest in this.List)


Test LobjTestNow = new Test();

LobjTestNow =(Test) LobjTest.Clone();



return LobjTestList;



Option 2: Serializing

Mark all the classes that are involved in copying as [Serializable] and use the below code to clone any object.

Suppose if we need to clone TestList, mark it as [Serializable] and place the following method in TestList class. This method copies an object using memory streams.

public TestList CopyTestList()


MemoryStream ms = new MemoryStream();

MemoryStream BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));

bf.Serialize(ms, this);

ms.Seek(0, SeekOrigin.Begin);

TestList LobjTestListClone; LobjTestListClone = (TestList)(bf.Deserialize(ms));


return LobjTestListClone;


Post a Comment

cigos emmanuel said...

Very Nice article , but you doesn´t post the namespaces using.

anoop said...

i am using crystal report 8 in visual studio 2008 c# back end sqlserver2008. I want to print 3 copies of Invocie. Like first copy should be marked as "Original" Second "Accounts" and third "Record Copy".