Deep copy of Objects in C# Metro for Windows RT/WoA

Hey Guys! I don’t write blogs as much as I should. I swear I have tons of fun little snippets of code that I use all the time. I just don’t post them. :X

Here’s a great one that I’ve just finally figured out. Deep Copy in C# for Metro is very tricky. All the examples you will find are based on older version of .NET that aren’t included or are deprecated completely in Windows RTM.

Here is a super simple helper function that you can easily throw in an extension class.
 

using System.IO;
using System.Runtime.Serialization;
using Windows.Foundation;

namespace Extensions
{
#pragma warning disable 1591
    public static class ObjectExtension
    {
        public static Object DeepCopy(this Object objectToCopy)
        {
            Object copy;
            DataContractSerializer serializer = new DataContractSerializer(typeof(Object));
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, objectToCopy);
                ms.Position = 0;
                copy = (Object)serializer.ReadObject(ms);
            }
            return copy;
        }
    }

#pragma warning restore 1591
}

In the example class above, you can easily swap out Object for any Class type you want. I wanted to make this generic but couldn’t get it working. If you can, more power to ya! 🙂

I personally have a Data object in place of Object. One gotcha that you may run into is classes with an ImageSource property or another property that can’t be serialized. You need to add these metadata tags to your class to define which properties are supposed to be copied and which are ignored.

[DataContract]
class DataClass

[DataMember]
String title { get; set;}

[IgnoreDataMember]
ImageSource imageSource { get; set;}

More info can be found in the msdn: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

Leave a Comment

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

  Wordpress Theme Protected By Wp Spam Blocker