Using generics with XmlSerializer

Posted by MainMa on Stack Overflow See other posts from Stack Overflow or by MainMa
Published on 2010-04-19T19:22:16Z Indexed on 2010/04/19 19:33 UTC
Read the original article Hit count: 522

Hi,

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);
    }
}

© Stack Overflow or respective owner

Related posts about generics

Related posts about xml-serialization