Using generics with XmlSerializer

Arseni Mourzenko picture Arseni Mourzenko · Apr 19, 2010 · Viewed 23.1k times · Source

When using XML serialization in C#, I use code like this:

public MyObject LoadData()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        return (MyObject)xmlSerializer.Deserialize(reader);
    }
}

(and similar code for deserialization).

It requires casting and is not really nice. Is there a way, directly in .NET Framework, to use generics with serialization? That is to say to write something like:

public MyObject LoadData()
{
    // Generics here.
    XmlSerializer<MyObject> xmlSerializer = new XmlSerializer();
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        // No casts nevermore.
        return xmlSerializer.Deserialize(reader);
    }
}

Answer

Filip Ekberg picture Filip Ekberg · Apr 19, 2010

An addition to @Oded, you can make the method Generic aswell:

public T ConvertXml<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(new StringReader(xml));
}

This way you don't need to make the whole class generic and you can use it like this:

var result = ConvertXml<MyObject>(source);