Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Any idea why this behaviour is different?

like image 856
Joan Venge Avatar asked Nov 09 '09 21:11

Joan Venge


People also ask

Can a dictionary have a null key C#?

Dictionary will hash the key supplie to get the index , in case of null , hash function can not return a valid value that's why it does not support null in key.

Can you index a dictionary C#?

Access Dictionary Elements Using Index var element = capitals. ElementAt(2); The ElementAt method provides us array-like access capability to key-value pairs of Dictionary<string, string> . As with C# arrays, the index of the first element is 0.

Can a dictionary have a null key?

Dictionaries can't have null keys.

Can a dictionary have a null value?

It is totally legal to have NULL values in dictionaries or key-value pairs in both c# and/ or JavaScript. In C# it is correct to do something like var fullName = meta["FullName"] and then fullName equals NULL . If the Serializer removes all NULL values, you are forced to test with Meta. ContainsKey or Meta.


2 Answers

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.

like image 178
Darin Dimitrov Avatar answered Oct 05 '22 21:10

Darin Dimitrov


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.

like image 29
Matthew Avatar answered Oct 05 '22 21:10

Matthew