Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always use TryGetValue to access .net Dictionaries?

Tags:

.net

exception

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...

like image 938
Brann Avatar asked May 20 '09 09:05

Brann


People also ask

Why use TryGetValue?

Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property. This method approaches an O(1) operation.

What are the best and safest ways to get a value out of a dictionary for a key C#?

Just use the Dictionary provided indexer: listaFirme[matchKey] . This returns the related value. IF the key does not exist the Dictionary throws a KeyNotFoundException exception. If you want to check if the key exists you can use the ContainsKey() method which returns a bool .


1 Answers

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.

like image 124
Jon Skeet Avatar answered Sep 18 '22 23:09

Jon Skeet