Over a million developers have joined DZone.

Mythbusters: Use An Array Because It Is The Only Collection That Can Be Serialized

·

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!

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}