As an icebreaker question, I’ve asked several interviewees to name classes that one might find in the System.Collections namespace.  There a quite a few answers to this questions – especially if you start to explore the System.Collections.Specialized namespace.  Though I completely understand why folks might immediately shout out answers like Hashtable, Stack, Queue or ArrayList, I am still surprised that never once did any candidate every mention System.Collections.Specialized.HybridDictionary.  It’s a shame, too, because it’s pretty cool.

One should consider the size of the collection before choosing a container.  If, for example, you are dealing with a small number of items, you might not want to use a Hashtable since there are some noted inefficiencies.  On the other hand, using ListDictionary for larger lists it is not efficient at all.  Therefore, one might appropriately chose a ListDictionary for small collections and a Hashtable for larger ones.  But what do you do if you aren’t sure how large your collection is going to be? 

That’s where the HybridDictionary comes in.  The HybridDictionary – emphasis on Hybrid – will internally use a ListDictionary while the count is less than or equal to 10 and only when the list becomes larger does it convert to using a Hashtable. The HybridDictionary is best used in situations where some lists are small and others are very large or you just aren’t sure how big a list might eventually grow. 

If you ask me, the HybridDictionary’s ability to migrate from one type to another is a neat trick.  Of course, there are a couple of things you still need to consider:

  1. What’s the overhead associated with the conversion?  Fortunately, if the starting item count is greater than 10, the HybridDictionary will start out with the Hashtable to reduce the overhead generated by the conversion.  However you still have to ask if the cost of further conversions is greater than, say, having a Hashtable manage a small sample of data?  
  2. We have to consider generics.  If you are wondering about the HybridDictionary’s generic equivalent, it’s the Dictionary<>.  The same goes for the Hashtable and ListDictionary; their generic complement is Dictionary<> as well. The point is once you start using generic equivalents, the choice of which collection type to use is pretty much decided for you. 

All the same, the HybridDictionary is really slick even if the only time you get to use it is on an interview.

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>