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

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 serialized (or put differently, no other collection can be serialized).

For this, I’m assuming serialized means to XML, and it also means serialized easily. In theory, anything can be serialized—it’s just a concept—but I’m assuming easily, i.e., no custom code outside invoking built-in framework serialization.

Serialization with XmlSerializer

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 it spits out XML. It also works perfectly with ArrayList and List<T>. This does fail with LinkedList<T> and Dictionary<T, K>, which is annoying.

Serialization with DataContractSerializer

The myth, I think, comes from a lack of knowledge of what’s in the .NET Framework—in this case, thinking there’s only one way to serialize something when the framework ships with many of them. So let’s 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, arrays, ArrayList, List<T>, LinkedList<T>, and Dictionary<T, K> are all serialized!

Myth Outcome

BUSTED! There’s a simple way to serialize collection classes in the framework—so arrays are not the only thing that can be serialized!

Attachments