If I’m using a Hashtable, I can write code like this:
object item = hashtable[key] ?? default_value;
That works whether or not key appears in the Hashtable.
I can’t do that with a Dictionary<TKey. TValue>. If the key’s not present in the dictionary, that will throw a KeyNotFoundException. So I have to write code like this:
MyClass item; if (!(dict.TryGetValue(key, out item)) { item = default_value; }
I’m wondering why this is. Dictionary<TKey, TValue> is just a wrapper around Hashtable. Why has this restriction been added to it?
Edit:
For another perspective on PopCatalin’s answer (see below), the code I’d written above won’t work if the dictionary’s values are of a value type. If I’m using a Dictionary<int, int>, then the code I would like to use looks like this:
int i = dict[key] ?? default_value;
And that won’t compile, because dict[key] isn’t a nullable or reference type.
The difference between a
Dictionary<T>and aHashtableis that aDictionary<T>is a generic type that can specialize to store value types along reference types.The hashtable can only store reference types (a
Objectpassed by reference) and only value types that are boxed (also passed by reference).When a dictionary is specialized with value types, it must return those values ‘by value’ not by reference.So, therefore, a
Dictionary<T>can’t return null, as null is not a valid value for value types.