Wednesday, June 13, 2012

Generic Serialization and Deserialization


// Serialization

public static string SerializeToXml<T>(T value)
    {
           using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
           {
                  XmlSerializer serializer = new XmlSerializer(typeof(T));
                  serializer.Serialize(writer, value);
                  return writer.ToString();
           }
    }


//Deserialization

public static T Deserialize<T>(string input) where T : class
{
          System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
          using (StringReader sr = new StringReader(input))
                 return (T)ser.Deserialize(sr);
       }

No comments: