Silverlight C# Object Deep Copy /Clone

June 16, 2011 — admin

Silverlight C# Object Deep Copy /Clone

There are two types of class/object clone.
1) Shallow Clone:
 

- you simply create a copy of a class/object and keep a pointer to another object of the same type.

Ex:

MyObject origin = new MyObject();

MyObject newCopy = orgin;

- Doing it this way, also mean whether you modify data in origin or newCopy, both object data will be changed, because it actually point to the same object.

2) Deep Clone:

- You completely make a copy/clone of an object

- Here I’ll have an example of how to do DeepClone/DeepCopy of an object in C#

Something you need to know before we do so is Extention Method.
Extension Method:

- C# has an ExtensionMethods class which allows you to add any static method to it. Any static methods within this ExtensionMethods class can be called from other object as if it's part of that object

-> Object that call the extension method must be the same type as the extention method parameter datatype. We often use T for generic type, so it can be anything.

 

Definition from Microsoft as follow:

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type"

HOW TO CREATE A DEEP COPY?
For DeepCopy, we implement it using extension method as well:

/*

* Author: Di Tran

* Date: 06-10-2011

* Description: Create this class to add extension method

* - Added DeepCopy method to object

*/

 

using System.IO;

using System.Runtime.Serialization;

 

namespace DiTran.ClassLibrary

{

//Required using System.Runtime.Serialization;

//- Silverlight doesn't have it in its plugin, have to add reference to your project

public static class ExtensionMethods

{

public static T DeepCopy<T>(this T theSource)

{

T theCopy;

DataContractSerializer theDataContactSerializer = new DataContractSerializer(typeof(T));

using (MemoryStream memStream = new MemoryStream())

{

theDataContactSerializer.WriteObject(memStream, theSource);

memStream.Position = 0;

theCopy = (T)theDataContactSerializer.ReadObject(memStream);

}

return theCopy;

}

}

 

}

 

//Now you can make a copy/clone of an object completely

MyObject origin = new MyObject();

MyObject newCopy = origin.DeepCopy();

Happy coding.