Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I really need to write this "SerializationHelper"?

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!

like image 800
JoelFan Avatar asked Nov 15 '22 13:11

JoelFan


1 Answers

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?

like image 139
Christian Hayter Avatar answered Dec 17 '22 14:12

Christian Hayter