Should I check whether particular key is present in Dictionary if I am sure it will be added in dictionary by the time I reach the code to access it?
There are two ways I can access the value in dictionary
- checking ContainsKey method. If it returns true then I access using indexer [key] of dictionary object.
or
- TryGetValue which will return true or false as well as return value through out parameter.
(2nd will perform better than 1st if I want to get value. Benchmark.)
However if I am sure that the function which is accessing global dictionary will surely have the key then should I still check using TryGetValue or without checking I should use indexer[].
Or I should never assume that and always check?
Use the indexer if the key is meant to be present – if it’s not present, it will throw an appropriate exception, which is the right behaviour if the absence of the key indicates a bug.
If it’s valid for the key not to be present, use
TryGetValueinstead and react accordingly.(Also apply Marc’s advice about accessing a shared dictionary safely.)