开发者

Why does Dictionary[index] throws a KeyNotFoundException but Hashtable[index] doesn't?

Any idea why this behaviour开发者_如何学Go is different?


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜