SerializableDictionary and System.InvalidOperationException

0.00 avg. rating (0% score) - 0 votes

I recently attempted to use Paul Welter’s SerializableDictionary in one of my Windows Mobile projects, Everything seems to work well with no code motifications, until when I need to serialize a class containing 2 dictionaries:

public class AppConfig
      public SerializableDictionary Dictionary1;
      public SerializableDictionary Dictionary2;    


Attempt to serialize the above class will fail with a System.InvalidOperationException: Two mapping for dictionary. Searching the web for the exact error message returns no useful result, except for a posting which described a similiar problem (Two mappings for SourceTree.DTO.InventoryItemCollection.) but did not provide a solution. The posting also explicitly mentioned that the error occurred only on .NET Compact Framework, and not on the full framework.

The root cause of the error is at the first few lines of the SerializableDictionary source code:


public class SerializableDictionary
    : Dictionary, IXmlSerializable

With this declaration, when 2 SerializableDictionary stay in the same class (which will be serialized), there will perhaps be a conflict somewhere as both of them are set up to use the same XmlRoot element (“dictionary”).

A workaround is not to define XmlRoot inside SerializableDictionary class, but to create another class inheriting from SerializableDictionary and define XmlRoot in this class:

//parent class: SerializableDictionary
public class SerializableDictionary
    : Dictionary, IXmlSerializable { …. }
//dictionary 1
public class SerializableDictionary1 : SerializableDictionary { }
//dictionary 2
public class SerializableDictionary2 : SerializableDictionary { }
//the class to be serialized
public class AppConfigNew
      public SerializableDictionary1 Dictionary1;
      public SerializableDictionary2 Dictionary2;    

This requires a few more lines of code, but is the cleanest workaround I have found. Also, I have yet to figure out why the full framework does not have such a problem.

0.00 avg. rating (0% score) - 0 votes


A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>