« Updated PHP guide | Main | Updated PHP Install Guide »
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 {
[Serializable]
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 April 30, 2007 11:35 AM
Comments
So useful and simple !!! :)
It saves me couple of hours.
Thank you for this post.
Posted by: Nicolas Jolet at May 7, 2008 03:19 PM
thanks, you saved me a huge headache
:)
Posted by: giano at May 8, 2008 03:42 AM