Sloppy, sloppy, sloppy


While working on one of my home projects I noticed that I was misusing a Dictionary: I was pulling the keys and calling the .IndexOf() to give me an identity for the Dictionary entry:

index = states.Keys.IndexOf(state.signature);

The odd thing was that this worked!  It has worked consistently for many hundreds of runs. This indicates that the Dictionary class is keeping its entries in the order they are added – which seems weird. Aren’t Dictionary entries hashed?

A quick search on the all-knowing, all-seeing internet turned up an answer:  Dictionary stores its entries in an array and uses a separate table to store indices to the hashed values of the entry keys.  However, this is just the way that the Dictionary class was implemented – it is not part of the definition. This means you can’t rely on it being the case in the future: the next version of the .NET framework could implement Dictionary differently and the above code will not work.

Now I am worried that there are other places in my code where I have sloppily coded reliance on implementation side-effects of .NET. Aaarrrrggghhh!!!! How much code am I going to have to review to make sure it doesn’t break if I switch to the next version of .NET?

Lesson learned: look at the MSDN documentation carefully – note what is a documented feature and what you “just stumbled upon”.

I wonder how long it will take me to forget this one?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s