Serializable Dictionary

Whilst writing a WinForm with a TreeView I came across ye olde problem of using components that don’t support Serialization. In my case I was shadowing the TreeNodes with my own Dictionary object, actually a generic myDictionary<string, myObject> only to discover that Dictionary doesn’t support Serialization either
 
So faced with writing some custom serialization code I quickly reached for Google and found…
 
So now I had a serializable dictionary I just had to sort out my components. The first annoying problem was that my component contains a field of type TreeNode. So like a good .net developer I added the NonSerialable attribute to the field. But when I went to serialize the component it complained it couldn’t find out what a TreeNode was, grrr. So the mere fact of exposing a public property of TreeNode, even though the resulting serialization won’t use it, is enough to fail the XmlSerializer. I’ve not thought too much about a solution to this since I only use this class internally so I changed the property from Public to Internal and that did the trick…although what if I did need to expose that as a public method? So the code now happily writes my dictionary of objects to disk.
Advertisements
This entry was posted in cSharp. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s