Why doesn't XmlSerializer support Dictionary?

theburningmonk picture theburningmonk · May 26, 2010 · Viewed 35.9k times · Source

Just curious as to why Dictionary is not supported by XmlSerializer?

You can get around it easily enough by using DataContractSerializer and writing the object to a XmlTextWriter, but what are the characteristics of a Dictionary that makes it difficult for a XmlSerializer to deal with considering it's really an array of KeyValuePairs.

In fact, you can pass an IDictionary<TKey, TItem> to a method expecting an IEnumerable<KeyValuePairs<TKey, ITem>>.

Answer

leppie picture leppie · May 26, 2010

Hashtables need hashcode and equality comparer providers generally. These cant be serialized easily in XML, and definitely will not be portable.

But I think you already found your answer. Just serialize the hashtable as a List<KeyValuePair<K,V>> and then (re)construct it into a hashtable.