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?
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?
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 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)
}
Alternatively to using TryGetValue
, you can first check if the key exists using dict.ContainsKey(key)
thus eliminating the need to declare a value prior to finding out if you'll actually need it.
I think you can try a
dict.ContainsKey(someKey)
to check if the Dictionary contains the key or not.
Thanks