So, I’ve found a piece of code like this:
class CustomDictionary
{
Dictionary<string, string> backing;
...
public string Get(int index)
{
return backing.ElementAtOrDefault(index); //use linq extensions on IEnumerable
}
}
And then this was used like so:
for(int i=0;i<mydictionary.Count;i++)
{
var value=mydictionary.Get(i);
}
Aside from the performance problems and uglyness of doing it this way, is this code actually correct? Ie, is the IEnumerable on Dictionary guaranteed to always return things in the same order assuming that nothing is modified with the dictionary during the iteration?
This is NOT guaranteed. It is for a SortedDictionary<>, of course, and also for arrays and lists. But NOT for a Dictionary.
Chances are, it will be stable if the dictionary is not changed – but it’s just not guaranteed. You have to ask yourself – do you feel lucky? 😉