Dictionary: SerializationException
Wednesday, December 30th, 2009When you to inherit your custom dictionary from Dictionary
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.
Recently me and my team realized that several our queries, that include maximum limit on the recordset, are limited in the web application and not on the Oracle side.
This is a good advice for all creating applications using .NET that need to work on both Microsoft .NET and Mono.
