« February 2007 | Main | July 2007 »

April 30, 2007

Serializing a generic dictionary in .NET 2.0 using the BinaryFormatter

When using the BinaryFormatter to serialize a strongly-typed dictionary that extends System.Collections.Generic.Dictionary<>, I found out that one must add a constructor that accepts SerializationInfo and StreamingContext parameters, then just passes those on to the base class:

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace MyNamespace.DataTypes {
public class MyDictionary: Dictionary {
public MyDictionary()
: base() {
public MyDictionary(SerializationInfo info, StreamingContext context)
: base(info, context) {

The error I was getting was, "System.Runtime.Serialization.SerializationException: The constructor to deserialize an object of type 'MyNamespace.DataTypes.MyDictionary' was not found."

I got the idea here: http://www.vbforums.com/showthread.php?t=314430, which has the code example in VB.NET.

To serialize Dictionary objects using an XML serializer, you have to implement a custom dictionary as described here: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.

Posted by Peter at 11:35 AM | Comments (2)