Alex Rivera | Logout

Should I always use TryGetValue to access .net Dictionaries?

Asked 2009-05-20T09:46:12.740
10

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

Edit
Report

1 Answer

2

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.

answered 2009-05-20T09:53:47.857

Your Answer