jjnguy
jjnguy

Reputation: 138884

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

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?

Upvotes: 24

Views: 17951

Answers (4)

Viking22
Viking22

Reputation: 561

I think you can try a

dict.ContainsKey(someKey)

to check if the Dictionary contains the key or not.

Thanks

Upvotes: 5

Kon
Kon

Reputation: 27441

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.

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1062865

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

Upvotes: 25

Jon Skeet
Jon Skeet

Reputation: 1500675

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.

Upvotes: 14

Related Questions