I am working on a small project to learn how to serialize an object in C#.NET I created the following class that is the class I am attempting to serialize:
p
The problem is that you are losing the contents of your surrogate List<DictionaryEntry> DictionaryStringInt
property during deserialization. The workaround is to change it to an array:
DictionaryEntry [] DictionaryStringInt
{
get
{
if (dictionaryStringInt == null)
return null;
List<DictionaryEntry> list = new List<DictionaryEntry>();
foreach (KeyValuePair<string, int> element in dictionaryStringInt)
{
list.Add(new DictionaryEntry(element.Key, element.Value));
}
return list.ToArray();
}
set
{
if (value == null)
return;
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach (DictionaryEntry entry in value)
{
dictionary.Add(entry.Key, entry.Value);
}
dictionaryStringInt = dictionary;
}
}
For an explanation of why a List<DictionaryEntry>
surrogate property fails during deserialization, see Cannot deserialize XML into a list using XML Deserializer. As explained there:
XmlSerializer
calls the getter to get the list. If null, it allocates a list and sets it via the setter. It holds onto the list in some local variable while reading it.
It deserializes each list element, and adds it to the list it is holding.
And that's it. It never calls the containing class's list property setter afterwards. Thus the contents of the list are never populated into your dictionary.
But, since an array cannot be resized once allocated, it must be allocated and set back after its contents are read and deserialized. Thus, an array property can function as a surrogate during deserialization.