I understand that a dictionary is not an ordered collection and one should not depend on the order of insertion and retrieval in a dictionary.
However, this is what I noticed:
- Added 20 key value pairs to a Dictionary
- Retrieved them by doing a foreach(KeyValuePair…)
The order of retrieval was same as the order in which they were added.
Tested for around 16 key value pairs.
Is this by design?
It’s by coincidence, although predictably so. You absolutely shouldn’t rely on it. Usually it will happen for simple situations, but if you start deleting elements and replacing them with anything either with the same hash code or just getting in the same bucket, that element will take the position of the original, despite having been added later than others.
It’s relatively fiddly to reproduce this, but I managed to do it a while ago for another question:
The results show 10, 1, 2 rather than 1, 2, 10.
Note that even though it looks like the current behaviour will always yield elements in insertion order if you don’t perform any deletions, there’s no guarantee that future implementations will do the same… so even in the restricted case where you know you won’t delete anything, please don’t rely on this.