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?
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) }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With