Cloning Entities in Silverlight

Here's a nice little extension method that returns a deep copy of a relatively simple object - like an Entity or a Data Transfer Object. It is based on the DataContractSerializer, so the object should be serializable through XML or a DataContract.

The extension works from Silverlight 2 upwards:

public static class GenericExtensions

{

    public static T Clone<T>(this T source)

    {

        DataContractSerializer dcs = new DataContractSerializer(typeof(T));

        using (MemoryStream ms = new MemoryStream())

        {

            dcs.WriteObject(ms, source);

            ms.Position = 0;

            return (T)dcs.ReadObject(ms);

        }

    }

}

Enjoy!