Monday, September 15, 2008

Tuesday, September 9, 2008

DeepCopy with Silverlight

In a few scenarios, the need arises for making an exact copy of a given object. I've been doing this for a few years now in Windows Forms development using code that looks something like:


Using the code above, one could copy any object just by typing:

SomeObjectType instance = anotherInstance.DeepCopy();

Unfortunately for Silverlight users, the BinaryFormatter is not available, so when I wanted to store the original state of an object (make a deep copy of it) retrieved from a service call in order to track changes on the client, I could not do it the old way :| .

DataContractSerializer to the rescue:
Thanks to recent SP1 changes which do not require objects to be marked with the DataContract tag, you can use the DataContractSerializer (which is available is Silverlight) to serialize just about any object of a given type. Here's the code for Silverlight Deep Copy:


Remember to add a reference to System.Runtime.Serialization to the project in order to get to the DataContractSerializer class.

EDIT: Recently came across this post, which may contain additional useful information.