Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: What does the [string] indexer of Dictionary return?

Tags:

What does the [string] indexer of Dictionary return when the key doesn't exist in the Dictionary? I am new to C# and I can't seem to find a reference as good as the Javadocs.

Do I get null, or do I get an exception?

like image 351
jjnguy Avatar asked Dec 29 '08 14:12

jjnguy


2 Answers

If you mean the indexer of a Dictionary<string,SomeType>, then you should see an exception (KeyNotFoundException). If you don't want it to error:

SomeType value; if(dict.TryGetValue(key, out value)) {    // key existed; value is set } else {    // key not found; value is default(SomeType) } 
like image 147
Marc Gravell Avatar answered Oct 10 '22 21:10

Marc Gravell


As ever, the documentation is the way to find out.

Under Exceptions:

 KeyNotFoundException The property is retrieved and key does not exist in the collection 

(I'm assuming you mean Dictionary<TKey,TValue>, by the way.)

Note that this is different from the non-generic Hashtable behaviour.

To try to get a key's value when you don't know whether or not it exists, use TryGetValue.

like image 42
Jon Skeet Avatar answered Oct 10 '22 19:10

Jon Skeet