Mythbusters: You should use an Array because it is the only collection that can be serialised

Submitted by Robert MacLean on Mon, 07/09/2012 - 13:04

Another in my theme of investigating claims that to me sound wrong, this time that arrays should be chosen over other collections because only arrays can be serialised (or put differently, no other collection can be serialised).

For this I am assuming serialised means to XML, and it also means serialised easily. In theory anything can serialised as it just a concept, which is why I am assuming easily – i.e. no custom code outside of invoking built in framework serialisation.

Serialisation with XmlSerialiser

private static string Serialise<T>(T o)
{
    var serializer = new XmlSerializer(typeof(T));
    var memoryStream = new MemoryStream();
    serializer.Serialize(memoryStream, o);
    memoryStream.Position = 0;
    using (var reader = new StreamReader(memoryStream))
    {
        return reader.ReadToEnd();
    }
}

With the above code you can pass in an array and spits out XML. It also works perfectly with ArrayList & List<T>. This does fail with LinkedList<T> and Dictionary<T,K> which is annoying.

Serialisation with DataContractSerializer

The myth I think comes from lack of knowledge of what is in the .NET Framework, in this case thinking there is one way to serialise something when the framework ships with many of them. So lets use DataContractSerializer this time and see:

private static string Serialise2<T>(T o)
{
    var serializer = new DataContractSerializer(typeof(T));
    var memoryStream = new MemoryStream();
    serializer.WriteObject(memoryStream, o);
    memoryStream.Position = 0;
    using (var reader = new StreamReader(memoryStream))
    {
        return reader.ReadToEnd();
    }
}

Using this Array, ArrayList, List<T>, LinkedList<T> & Dictionary<T,K> are all serialised!

Myth Outcome

BUSTED! There is a simple way to serialise the collection classes in the framework – so array’s are not the only thing that can be serialised!

File attachments