Search code examples
c#dictionarysymbol-table

Why Dictionary<TKey, TValue>.Item() throws exception on a key not found while IDictionary.Item() should not?


That's seems strange to me that the Dictionary.Item() method throws KeyNotFoundException while IDictionary.Item() does not. And Dictionary implements this interface. So why there is such implemenation that I image breaks interface convention?

(Also the symbol type structure which I image the idea behind Dictionary seems to have the convention that the method should not throw the exception.)


Solution

  • IDictionary is not generic, for example a HashTable implements it. So a HashTable's key and it's value are objects, hence it can (and indeed does) return null if a key was not found. A IDictioanary<TKey, TValue>'s value can be a value type, hence it has no "error"-value like null which can be returned instead.