Skip to content

Deep Copy For Custom Objects

One of the major issues i had working with database entities/custom objects in Silverlight/WPF was that since “class” is a reference type any changes made to the object would stay in all its copies!!.

Lets take an example

I have a custom class called Person and i want to show in a listbox all those who are parents.

so basically i have this piece of code.

List personList = new List();
private void ShowInitialParentList()
{
listboxParent.Datacontext = (from p in parentList
where p.IsParent
select p).ToList();
}

Now for some reason i have another listbox and i want to see what happens if all of them are parents(i don’t know why…just for this example:-))

so i do this

private void AssignSampleParents()
{
List templist= new List;
foreach (Person original in personList)
{
templist.Add(original);
}

foreach (person p in templist)
{
p.IsParent = true;
}
listboxSample.Datacontext = (from p in tempList
where p.IsParent
select p).ToList();
}

Now even though i copied the original list using the much cumbersome ADD method functionality(you can try direct assignment or AddRange or anything else you want!) what i get is that not only does the ListBoxSample show all the persons , even the original listbox gets updated..so basically making the copy was of no use!!

The only way to get out of this is to use the “Clone” method which is NOT available by default in custom/database entity objects.

Making a customized Clone method is a LOT of work for all the custom objects in your class….so the thing to do is…

Use the following Extension method!

using System.ComponentModel;
using System.Runtime.Serialization;
using System.IO;

public static class ExtensionMethods
{
public static T DeepCopy(this T oSource)
{

T oClone;
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
dcs.WriteObject(ms, oSource);
ms.Position = 0;
oClone = (T)dcs.ReadObject(ms);
}
return oClone;
}
}

Now if i did the following

foreach (Person original in personList)
{
templist.Add(original.DeepCopy());
}

everything would be perfect, because the object in the tempList has NO reference to the object in the original list!!

I found this piece of code a real keep!!..It will resolve a LOT of your “Who set this property issues”!

Do let me know if you “kept” this code for keeps!..

More such snippets coming up!

Cennest!!

Leave a Reply

Your email address will not be published. Required fields are marked *