This is a classic that I have pulled from my last blog’s archives, but I thought I would post it here because I find myself going back time and time again. It really is a great set of extension methods, especially if you need an instant object dump or you are creating a simple XML repository. These methods allow you to serialize to a string/XML and deserialize from a string to the type you specify.

public static class DataContractSerializationExtensions
    {
        #region Serialize
        public static string Serialize<T>(this T target)
        {
            return Serialize(target, null);
        }
        public static string Serialize<T>(this T target, IEnumerable<Type> knownTypes)
        {
            using (var writer = new StringWriter())
            {
                using (XmlWriter xmlWriter = new XmlTextWriter(writer))
                {
                    var ser = new DataContractSerializer(typeof(T), knownTypes);
                    ser.WriteObject(xmlWriter, target);
                    return writer.ToString();
                }
            }
        }
        #endregion
        #region Deserialize
        public static T Deserialize<T>(this string targetString)
        {
            return Deserialize<T>(targetString, null);
        }
        public static T Deserialize<T>(this string targetString, IEnumerable<Type> knownTypes)
        {
            using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(targetString)))
            {
                using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                {
                    var ser = new DataContractSerializer(typeof(T), knownTypes);
                    // Deserialize the data and read it from the instance.
                    return (T)ser.ReadObject(reader);
                }
            }
        }
        #endregion
    }

Have fun serializing and deserializing.