Prevent unnecessary dictionary lookups

I assume this might be applicable to more languages, but at least it is to C# and VB.NET. To prevent unnecessary dictionary lookups, IDictionary (and others) have TryGetValue() and TryAdd() to prevent code that first checks with ContainsKey() and then, in a new statement does another lookup.

As illustration, the most straight-forward case to think about:

Non-compliant

if (lookup.ContainsKey("some-key")
{
    var value = lookup["some-key"];
}

Compliant

if (lookup.TryGetValue("some-key", out var result)
{
    var value = result;
}

For the code analyzers by Microsoft, there is already such a rule, including a quick fix.

1 Like

Oops, I could have found that myself… #facepalm