views:

210

answers:

3

Any idea why this behaviour is different?

+4  A: 

So there will be no ambiguity between when the value of dictionary[key] stores a null value and when the key doesn't exist. Hashtable[key] will return null if it stores null or the key doesn't exist.

Matthew
+5  A: 

Here's the answer.

The primary reason Dictionary throws is that there is no "error" value that works over any V. Hashtable is able to return null because the key is always a reference type.

Darin Dimitrov
A: 

The primary reason Dictionary throws is political - had several options to preserve efficiency and ease of use. It actually provides a method (TryGetValue) which clearly demonstrates that claims about alleged "inability" to return sensible value are false. TryGetValue however forces distinctively awkward syntax to do exactly what indexer could have done easily.

C# templates provide easy way for constructing separate implementations for reference and value semantics and there are two other facilities for seamless handling of missing objects with value semantice which are used by tempates and some operators (default and nullable). Meaning that there was no rational reason to break the semantics of the hashtable.

It's a long terms political struggle between the academic notion of a collection which insists that everyone has to go through "do you have it" checks and real-life fact that such artificial procedure is inefficient and breaks thread safety - in principle (it breaks thread-safety of otherwise safe implementations by making acces non-atomic).

ZXX