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…
No, you’re entirely right IMO.
There’s no point in doing:
The only benefit of that over:
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.