I know that the order of a dictionary is undefined, MSDN says so:
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
Thats fine, but if I have two instances of a dictionary, each with the same content, will the order be the same?
I’m guessing so because as I understand, the order is determined by the hash of the keys, and if the two dictionaries have the same keys, they have the same hashes, and therefore the same order…
… Right?
Thanks!
Andy.
No it is not guaranteed to be the same order. Imagine the scenario where you had several items in the
Dictionary<TKey, TValue>with the same hash code. If they are added to the two dictionaries in different orders it will result in different orders in enumeration .Consider for example the following (equality conforming) code
The output of running this program is