views:

81

answers:

2

I just wrote this SerializationHelper class, but I can't believe this is necessary!

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

public static class SerializationHelper
{
    public static string Serialize<T>(T obj)
    {
        var outStream = new StringWriter();
        var ser = new XmlSerializer(typeof(T));
        ser.Serialize(outStream, obj);
        return outStream.ToString();
    }

    public static T Deserialize<T>(string serialized)
    {
        var inStream = new StringReader(serialized);
        var ser = new XmlSerializer(typeof(T));
        return (T)ser.Deserialize(inStream);
    }
}

And it's used like this:

var serialized = SerializationHelper.Serialize(myObj);

and:

var myObj = SerializationHelper.Deserialize<MyType>(serialized)

Am I missing something in the .NET framework? This is not rocket science!

+1  A: 

In actual fact, the bits where you call the .NET API are these:

var ser = new XmlSerializer(typeof(T));
ser.Serialize(outStream, obj);

var ser = new XmlSerializer(typeof(T));
var obj = (T) ser.Deserialize(inStream);

The rest of the code is your personal specialisation. I don't think that two lines of code is too much for calling an API. You could always condense them, e.g.

(new XmlSerializer(typeof(T))).Serialize(outStream, obj);

var obj = (T) (new XmlSerializer(typeof(T))).Deserialize(inStream);

Purely as an aside, I should point out that I regard storing XML data in string variables as a Code Smell. As soon as you take XML data out of its raw binary form (XDocument, XmlDocument, XPathDocument or any other type of DOM), you run up against encoding issues. What if a developer serialises an object to a string with encoding X, then writes the string to a disk file with encoding Y? Not very safe. Besides which, if encoding X is not UTF-16, how would you even represent the data in a .NET string?

Christian Hayter
You are missing a cast to T in your last line... otherwise I get an "object". And you are leaving out of your "condensing" the fact that I have to mention the type name explicitly a lot, which my solution obviates
JoelFan
Well spotted, I've edited the text.
Christian Hayter
Joel, I agree, it's a lot of typing. You have to ask yourself, at what point does writing a utility method to save yourself typing become a waste of time? If your methods genuinely save you time and make your code more readable, then that's great, keep them. All I am saying is, the designers of the `XmlSerializer` API did not happen to agree with you.
Christian Hayter
A: 

It's useful if you are doing any real amount (>1) of serialization/deserialization within a project. This was the case for me one time, so I just put a similar class in a Utils library, along with other reusable functions.

Grant Palin