tags:

views:

1464

answers:

4

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?

+9  A: 

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.

Jon Skeet
Thanks, The .net documentation is still kinda hard for me to wade through and find the info I need.
jjnguy
It's mostly pretty good (particularly the offline version, IMO - use the Index) but you need to know that to find the indexer documentation you usually look for the Item property.
Jon Skeet
Index...ok, I will remember this. I prefer dict.get(key) from Java. Oh well...I'm kind of a fan-boy.
jjnguy
Item, not Index. As for preferring the Java way - give it time. C# is a *much* nicer language than Java IMO. It takes a while to adjust, especially with the various new features of C# 3.0, but it's lovely :)
Jon Skeet
Jason
+8  A: 

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)
}
Marc Gravell
Thanks for an example of how to use the out thingy...ha.
jjnguy
The TryGetValue and TryParse examples are probably the most common "out" use-cases you'll see in most day-to-day code.
Marc Gravell
When I was reading about them I couldn't really see a great use. It just seems like a two return value hack.
jjnguy
+1  A: 

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.

Kon
+1  A: 

I think you can try a

dict.ContainsKey(someKey)

to check if the Dictionary contains the key or not.

Thanks

Vikas