Peter
Peter

Reputation: 38515

IDictionary indexer not consistent?

Why is the Indexer of a IDictionary not implemented the same way?

Look at Dictionary<Key, Value> if you try to access something that does not exist it throws a KeyNotFoundException.

If you do the same with a Hashtable it returns null.

https://dotnetfiddle.net/0cp5K7

Upvotes: 0

Views: 40

Answers (2)

Luaan
Luaan

Reputation: 63772

Two main reasons: generics and arbitrary restrictions.

First, for any reference type, null is a perfectly valid value, and separate from the existence or non-existence of a key in a dictionary. So Hashtable limits your ability to distinguish between a non-presence and a null value. This can hide errors.

Second, the dictionary type is generic, and allows value types. Value types have no notion of null, or anything similar.

As .NET progressed, more and more weight was put on preventing "bad paths" through code - making ambigous things obvious by making them an error by default. dictionary[42] means "I assume the dictionary contains the key 42, and I want the value associated with the key", just like array[3] means "I assume the array contains at least four elements, and I want the fourth one". Hashtable's treatment of the indexer is the weird one, not the other way around.

Upvotes: 2

zeromus
zeromus

Reputation: 1667

There's probably a lot of explanations and no one answer, but: How would a Dictionary<string,int> return null?

Upvotes: 1

Related Questions