Dictionary: SerializationException

When you to inherit your custom dictionary from Dictionary<k,V> class you’ll get nasty exception during deserialization:

System.Runtime.Serialization.SerializationException : The constructor to deserialize an object of type ‘SafeDictionary`2[System.String,System.String]’ was not found.

[Serializable]
internal class SafeDictionary<k, V> : Dictionary<k, V>
{
    public new V this[K key]
    {
            get
            {
                V value;
                if (this.TryGetValue(key, out value) == true)
                    return value;
                return default(V);
            }
            set
            {
                base[key] = value;
            }
    }

     public SafeDictionary()
    {
    }
};

Here’s the test:

[Test]
public void IsSerializable()
{
    SafeDictionary<string,string> dictionary =
        new SafeDictionary<string, string>();
    dictionary["key"] = "value";
    dictionary =
        SerializationHelper.SerializeAndDeserialize(dictionary);
    Assert.AreEqual("value", dictionary["key"]);
}

And serialization utility class:

class SerializationHelper
{
    public static T SerializeAndDeserialize<t>(T sm)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        using (MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, sm);
            stream.Position = 0;
            return (T)formatter.Deserialize(stream);
        }
    }
}

Dictionary class implements ISerializable interface.

The ISerializable interface implies a constructor with the signature constructor (SerializationInfo information, StreamingContext context).

At deserialization time, the current constructor is called only after the data in the SerializationInfo has been deserialized by the formatter. In general, this constructor should be protected if the class is not sealed.

So what you need to do is to add the following constructor:

    //Needed for deserialization.
    protected SafeDictionary(SerializationInfo information, StreamingContext context)
            : base(information,context)
    {
    }

Now the test will pass.

Tags:

Questions?

Consider using our Q&A forum for asking questions.

One Response to “Dictionary: SerializationException”

  1. Chris Says:

    Thank you !

    Without your article I would lost two hours (at least).

    On dot.net 4, I had to replace “protected” by “public” and I needed a simple constructor (no parameters) more. Except that, it works fine.