If I use Hashtable , I can write code like this:
object item = hashtable[key] ?? default_value;
This works if key appears in the Hashtable .
I cannot do this with Dictionary<TKey. TValue> Dictionary<TKey. TValue> . If a key that is not in the dictionary will throw a KeyNotFoundException . So I need to write code like this:
MyClass item; if (!(dict.TryGetValue(key, out item)) { item = default_value; }
I wonder why this is so. Dictionary<TKey, TValue> is just a wrapper around the Hashtable . Why was this restriction added to it?
Edit:
For another point of view on PopCatalin's answer (see below), the code I wrote above will not work if the dictionary values ββare of type value. If I use Dictionary<int, int> , then the code I would like to use is as follows:
int i = dict[key] ?? default_value;
And this will not compile because the dict[key] not a null or reference type.
source share