I just saw this behaviour and I\'m a bit surprised by it...
If I add 3 or 4 elements to a Dictionary, and then do a \"For Each\" to get all the keys, they appear in
Up to a certain list size it is cheaper to just check every entry instead of hashing. That is probably what is happening.
Add 100 or 1000 items and see if they are still in the same order.
What keys did you add with in your test, and in what order?
From what I know this shouldn't be a behavior to rely on. To check it quickly use the same elements and change the order in which you add them to the dictionary. You'll see if you get them back in the order they were added, or it was just a coincidence.
I hate this kind of "by design" functionalities. I think when giving your class such a generic name as "Dictionary", it should also behave "as generally expected". For example std::map always keeps it's key-values sorted.
Edit: apparently solution is to use SortedDictionary, which behaves similarly to std::map.
If you use .NET Reflector on the 3.5 class libraries you can see that the implementation of Dictionary actually stores the items in an array (which is resized as needed), and hashes indexes into that array. When getting the keys, it completely ignores the hashtable and iterates over the array of items. For this reason, you will see the behavior you have described since new items are added at the end of the array. It looks like if you do the following:
add 1
add 2
add 3
add 4
remove 2
add 5
you will get back 1 5 3 4 because it reuses empty slots.
It is important to note, like many others have, you cannot count on this behavior in future (or past) releases. If you want your dictionary to be sorted then there is a SortedDictionary class for this purpose.
The question and many of the answers seem to misunderstand the purpose of a hashtable or dictionary. These data structures have no specified behaviors with respect to the enumeration of the values (or in fact the keys) of the items contained in the data structure.
The purpose of a dictionary or hashtable is to be able to efficiently lookup a specific value given a known key. The internal implementation of any dictionary or hashtable should provide for this efficiency in lookups but need not provide any specific behavior with respect to enumerations or "for each" type iterations on the values or keys.
In short, the internal data structure can store and enumerate these values in any manner that it wishes, including the order that they were inserted.