Deep Copy / Clone Objects in Silverlight with C#
December 28, 2009
7 comments
The following code will add an extension method to Silverlight 3 based C# code to perform a deep copy of a custom object. This templated method uses the MemoryStream serialization/deserialization technique, but will not work with UIElement members or derivatives.
public static class ExtensionMethods
{
public static T DeepCopy<T>(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;
}
}
Categories: C#, Expression Blend, Silverlight
Clone, Deep Copy, Expression Blend, Extensions, Serialization



