tags:

views:

578

answers:

4

In another SO question, I've seen several people recommend me to always use TryGetValue.

While I always use TryGetValue over the Contains?/Access pattern, I avoid this pattern on purpose when I expect the key to always be in the dictionary. I then go for a direct indexer access, so that an exception is raised if the key isn't there, because something unexpected really happened (i.e. the key wasn't in the dictionary while I expect it to).

Since there seems to be a general consensus against my "best-practice" (3 out of 4 people on the post I mentioned explicitly advised to use TryGetValue at all time), I'm eager to read an extended discussion on that topic...

+1  A: 

If the absence of a key is exceptional, it's okay to raise an exception, imho.

VVS
+8  A: 

No, you're entirely right IMO.

There's no point in doing:

if (dict.TryGetValue(key, out value))
{
    // whatever
}
else
{
    throw new SomeException("key '" + key + "' wasn't in dictionary");
}

The only benefit of that over:

value = dict[key];

is that you get a more explicit exception message... but at the cost of readability, IMO.

It's like casting vs using as - an exception is the right result when the state is "wrong", so use the form which gives that behaviour.

Jon Skeet
You can add the actual key to the exception message if you do the TryGetValue/throw, which is something the default KeyNotFoundException fails to do (unless I'm missing something).
Skizz
A: 

If it is exceptional behavior for the key to not exist in your dictionary (which is what it sounds like), then it's fine to let the exception get raised if the key isn't found and let that exception propagate down the stack. If you want to use a defensive programming practice, you could use the following before you access the dictionary key:

Debug.Assert(Dictionary.ContainsKey(Key));

You only really need to use TryGetValue if you expect situations where the key may not exist, or if you want to have certain code run in the case of a key not existing.

Liron Yahdav
A: 

If the key is expected to be missing, using TryGetValue usually results in cleaner and more efficient code. If the key is expected to be present, then direct indexing access is usually better - the exception indicates a bug.

ContainsKey is usually only used if the corresponding value is not needed.

Barry Kelly