Friday, February 11, 2011

Deep Copy / Clone Objects in Silverlight with C#

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(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;
     }
}

3 comments:

  1. Just what I needed...thanks.

    ReplyDelete
  2. Have you got an other solution to clone UIElement in silverlight?
    Thanks

    ReplyDelete
    Replies
    1. As you probably have already discovered, the XamlWriter.Save() and XamlReader.Load() technique isn't available in Silverlight and doesn't work in partial trust scenarios. There are a couple of hand-rolled options that I've used with some degree of success, which you might find useful (or at least help you down the path):

      http://www.davidpoll.com/2010/07/25/to-xaml-with-love-an-experiment-with-xaml-serialization-in-silverlight/

      http://weblogs.asp.net/mehrantoosi/archive/2008/03/03/silverlight-s-xamlwriter.aspx

      http://projectsilverlight.blogspot.com/2009/10/silverlight-3-xamlwriter-v04.html

      Delete