2015-05-28

Enumerating dictionaries

When people work with the Dictionary class in .Net there are two common assumptions that I see used a lot. Worst part is that these assumptions are both wrong.

First we have the assumption that when you enumerate a dictionary you get objects in the order of the key (or the hash of the key). This is very easy to test and prove that this is not true.

But when you test that you might notice that the order of the key and value enumerators is in the order of insertion! However if you look in the remarks section for these properties you can see that the order is undefined. You can again easily test this by adding three items, remove one of them and then add a fourth item. Enumerating that collection will show that it looks like the last item takes the position of the removed item.

So should you use all this knowledge? No! The documentation says this is undefined because it allows for the implementation to be optimized without changing the guaranteed behavior.

No comments:

Post a Comment