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?
2 Answers
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.
3 Comments
Timores
You're correct about dictionaries, but exceptions CAN be serialized.
M.A. Hanin
@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.
Timores
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.
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);
XmlSerializer?BinaryFormatter?DataContractSerializer?NetDataContractSerializer? JSON? proto bufs? SOAP? I'm afraid each has subtly different behaviour. Many (not all) do support dictionary serialization. You also may need additional steps if you've done custom serialization (ISerializableetc).