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.