Does the Enumerator of a Dictionary<TKey, TValue> return key value pairs in the order they were added?

Viewed 5174

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?

7 Answers

Is this by design? It probably wasn't in the original .Net Framework 2.0, but now there is an implicit contract that they will be ordered in the same order as added, because to change this would break so much code that relies on the behaviour of the original generic dictionary. Compare with the Go language, where their map deliberately returns a random ordering to prevent users of maps from relying on any ordering [1].

Any improvements or changes the framework writers make to Dictionary<T,V> would have to keep that implicit contract.

[1] "Since the release of Go 1.0, the runtime has randomized map iteration order. ", https://blog.golang.org/go-maps-in-action .

Related