Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C# Dictionary<string, List<string>>.GetObjectData() (serialization) Consistent?

I know Dictionaries don't store their key-value pairs in the order that they are added, but if I add the same key-value pairs (potentially in different orders) to two different Dictionaries and serialize the results, will the data on file be the same?

Edit: To clarify, I'm asking specifically about the output of GetObjectData(), not any particular serializer. Consider the following code:

Dictionary<string,List<string>> dict1 = new Dictionary<string,List<string>>();
Dictionary<string,List<string>> dict2 = new Dictionary<string,List<string>>();
string key11 = "key1";
string key12 = "key1";
string key21 = "key2";
string key22 = "key2";
List<string> values11 = new List(1);
List<string> values12 = new List(1);
List<string> values21 = new List(1);
List<string> values22 = new List(1);
values11.add("value1");
values12.add("value1");
values21.add("value2");
values22.add("value2");
dict1.add(key11, values11);
dict2.add(key22, values22);
dict1.add(key21, values21);
dict2.add(key12, values12);

Will dict1 and dict2 return the same thing for GetObjectData()? If not, why not?

like image 988
Shea Levy Avatar asked Apr 22 '11 13:04

Shea Levy


2 Answers

Whether or not it is would end up being an implementation detail that likely would not be guaranteed in future versions and/or alternate implementations; As such, I would recommend at the very least having a test written that verifies it and can run as part of your standard tests. But if you are implementing a solution that absolutely depends on it, then it may be worth writing your own serializer...

like image 102
Chris Shaffer Avatar answered Oct 02 '22 13:10

Chris Shaffer


Almost certainly not! The Dictionary works by hashing, and there has to be some method of hash collision resolution. So let's say that the first time you go through the dictionary you add key1 and key2 in that order. key1 ends up in the "normal" spot for keys that hash to that particular value. key2 is stored "somewhere else" (dependent on the implementation).

Now change the order that you add keys. key2 goes in the normal spot and key1 goes "somewhere else."

You cannot make any assumptions about the order of the items in your dictionary.

Even if you could guarantee the order, that guarantee could be invalidated with the next change to the .NET Framework because the implementation of string.GetHashCode might change (it has in the past). That would completely change the order in which keys are stored in the dictionary's underlying data structures, so any saved data created by a previous version of the Framework would likely not agree with data you create when running with the new version.

like image 22
Jim Mischel Avatar answered Oct 02 '22 12:10

Jim Mischel