Wednesday, July 14, 2004 2:04 PM
pgolde
Should dictionaries be allowed to have "null" keys?
Should it be allowed to add a key-value to a dictionary with a “null” key?
It seems like it could be useful; after all, null is a valid value of reference types and so should be storable into a dictionary.
I began implementing OrderedDictionary to allow null keys. However, as I was getting into it and coding it, it became apparent that the IDictionary interface does not allow null keys. This is apparent in a couple of ways:
1) The documentation for IDictionary.Add and IDictionary<K,V>.Add states that an ArgumentNullException is thrown if key is null.
2) When doing a for each on IDictionary, you get back DictionaryEntry objects. When doing a for each on IDictionary<K,V>, you get back KeyValuePair objects. The constructors for DictionaryEntry and KeyValuePair throw exceptions if key is null.
So, it seems like there are three choices:
1) Allow OrderedDictionary to have null keys, but “fake” it when necessary. For example, when enumerating the dictionary via IDictionary.GetEnumerator, skip the entries with null keys. This seems iffy and possibly could mess you up in subtle ways, but it is technically doable.
2) Disallow OrderedDictionary to have null keys. This seems most in keeping with the “work as seamlessly as possible with the existing BCL” design principle. But it does disallow apparently useful functionality.
3) Ask Microsoft to fix DictionaryEntry and KeyValuePair so they allow null keys. Allow implementations of IDictionary to allow or disallow null keys as they see fit.
What do people think? How important is allowing null keys in dictionaries?