Hi when i am trying to serialize a dictionary, everything worked fine. but when i am deserializing it is showing count as 0. But, it works fine with a list. What is goingon exactly when we are deserializing a list and a dictionary?
+3
A:
Dictionaries don't really support serialization. This is a known issue which troubles many programmers, so if you Google ".NET Dictionary Serialization" you'll get many results with "how-to"s and workarounds.
This blog post, for example, suggests you use the KeyedCollection class instead.
M.A. Hanin
2010-03-04 09:55:32
You're correct about dictionaries, but exceptions CAN be serialized.
Timores
2010-03-04 10:03:05
@Timores, I've erased the part about exceptions.I had trouble serializing exceptions due to a contained Dictionary member, but that may be related to a specific type of exception i was serializing, or to the fact i was using the XmlSerializer, or maybe even to the fact I was using VB. In any way, I don't think you can generally say that all exceptions are serializable, I suspect the truth is somewhere in between. Please elaborate if you have additional info on this subject.
M.A. Hanin
2010-03-04 10:09:59
In general, not all classes are serializable, I agree. And we have to define whether we are talking about binary serialization or XML serialization. I was thinking of the former, where you can implement ISerializable in order to take over the serialization process and serialize a class with an embedded dictionary.You can use any .NET language, by the way, they are all semantically equivalent.
Timores
2010-03-04 10:20:56
+1
A:
If you use .Net 3.5 you can use the DataContractSerializer which will serialize a dictionary. It's also faster than a BinaryFormatter or XmlSerializer.
using System.Runtime.Serialization;
var dict = new Dictionary<string, string>();
dict.Add("a","a");
DataContractSerializer dcs = new DataContractSerializer(dict.GetType());
MemoryStream byteStream = new MemoryStream();
dcs.WriteObject(byteStream, dict);
byteStream.Position = 0;
var dict2 = dcs.ReadObject(byteStream);
Mikael Svenson
2010-03-04 10:16:08