Sunday, October 14, 2007

Serializable dictionary in C#

Did you ever need to serialize a generic key-value dictionary like the Dictionary class? Well in .Net that class is not serializable, in fact the interface IDictionary is not serializable for some unknown reason so all the classes that implement the IDictionary interface (SortedDictionary , Dictionary ) can not be serialized unless you specify some custom code.
The best code I have found online is written by Paul Welter and you can see it here. I needed to implement a SortedDictionary so the only change I made to that code is implement the SortedDictionary instead of the Dictionary.

3 comments:

Anonymous said...

"it's not serializable" that's all I needed. Thanks for the quick info :)

Janosz said...

You can find another implementation under following link: Serializable dictionary

Jocelyn Hotte said...

I've been able to work around this problem. It may not work for all use cases, but will work for most. Instead of using the XmlSerializer (which begins to age in comparison of other .Net serializers), I used XamlServices, here's a bit of code:

var values = new Dictionary();
values.Add("MY KEY", "MY VALUE");
var builder = new StringBuilder();
XamlServices.Save(new StringWriter(builder), values);
var data = builder.ToString();
MessageBox.Show(data);

var result = (IDictionary)XamlServices.Load(new StringReader(data));
MessageBox.Show(result.ToString());

And that worked for me.