C#

C#

By DeepSource

Consider using `.TryGetValue` to access elements in `Dictionary`CS-P1005

Performance

The .ContainsKey method allows you to check if a key exists in a Dictionary while the indexer, i.e. [] allows you to directly access the specified key's value. Using both of them means that you'd be effectively accessing the Dictionary twice. As an alternative, you can use .TryGetValue to get a value from a Dictionary that returns a bool depending on whether the key exists or not.

Examples

Bad Practice

if (dict.ContainsKey(key))              // 1st access to `dict`
    Console.WriteLine(dict[key]);       // 2nd access to `dict`

Recommended

if (dict.TryGetValue(key, out var val))
    Console.WriteLine(val);

Reference