Stupid Question 181 & 182: Lookup or Dictionary? (And what is Lookup)
I was refactoring my Leap Motion demo code earlier today and had one of my colleagues from Telerikhelp me out, Jeffrey Fritz. A second pair of eyes is extremely valuable for code reviews (Stupid Question 103: What are some different types of code reviews?), not just for code quality – but also to learn something new.
The library I was using had the Gesture types as enums, and somewhere in my code was a big old ugly switch. I made a comment about a ‘that’s what you get for using enums’ (jokingly) and Jeff said, ‘Well, in that particular case you could use a lookup dictionary’). I was confused. Lookupor dictionary? You see, in case you didn’t know there is a class called Lookup, and then there is the Dictionary class. What is even more confusing is that the term lookup dictionary also exists, it might or might not refer to an actual class :D Now, for my particular case it made more sense to use a Dictionary, but I’ve used Lookup quite a few times.
Lookup or Dictionary? (And what is Lookup)
Dictionary and Lookup can be used as lookup structures, but there are some differences between the two.
Lookup has no public constructor and is immutable. Immutable means that we cannot add or remove items after creation. (‘Stupid’ Question 30: What do we mean by immutable and mutable in OO?)
Lookup can have duplicate keys
Lookup is created by the factory method ToLookup() found on classes that implement IEnumerable
Searching for a non-existing key will return an empty sequence instead of an exception
Another big difference is that Lookup maps to a collection of values, not a single value like Dictionary does.
I ended up choosing Dictionary and making it readonly as the values were just strings, the keys where unique, and for me creating a collection with enums and then use a method to create a Lookup seemed like the wrong way to go. Performance wise I’ve been told the two don’t differ, but I haven’t tested that myself.
I’m curious to see if I’ve missed something above in regards to differences, which use scenarios you can think of, and why one should choose one over another?
Last modified on 2013-04-28