Useful generic example

The following is a great example of the use of generics to provide strongly typed serialization:

using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SerilizationTest
{
    static class Pickler
    {
        public static T UnPickle<T>(Stream s)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            return (T)xs.Deserialize(s);
        }

        public static void Pickle<T>(Stream s, T o)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(s, o);
        }

        public static string Pickle<T>(T o)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringWriter sr = new StringWriter();
            xs.Serialize(sr, o);
            return sr.ToString();
        }

        public static T UnPickle<T>(string s)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(s);
            return (T)xs.Deserialize(sr);
        }

        public T UnPickle<T>(XmlNode node)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(node.OuterXml);
            XmlReader xr = XmlReader.Create(sr);
            return (T)xs.Deserialize(xr);        
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s