views:

160

answers:

2

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);
    }
}
+4  A: 

Make your serialization class/method generic:

public T LoadData<T>()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        return (T)xmlSerializer.Deserialize(reader);
    }
}
Oded
Refactor that code! ;)
Filip Ekberg
@Filip - Quite right... I forgot the generic parameter...
Oded
That's what I'm doing in most of my projects. But I just wondered why this is not embedded in last versions of .NET Framework.
MainMa
A: 

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);
Filip Ekberg
Accepting this answer, rather than Oded one, because this one does not require class, and in fact, most of the time, I don't want to create one (for example when, in a small project, all XML data is accessed from one class).Thanks to everyone for answering.
MainMa
Why was this answer accepted? It contains a code error (semicolon in using) and XmlSerializer class is not IDisposable, therefore cannot be used in a using scope, so it won't compile for two reasons...
Koen
@Koen, sorry missed that, thanks for the heads up. Corrected it.
Filip Ekberg