Prefer the 'IDictionary.TryAdd(TKey, TValue)' method
Prefer the 'IDictionary.TryAdd(TKey, TValue)' method
Microsoft docsDescription
Both System.Collections.Generic.Dictionary2.ContainsKey(0) and System.Collections.Generic.Dictionary2.Add perform a lookup, which is redundant. System.Collections.Generic.Dictionary2.Add also throws an exception if the key is already present in the dictionary. It's more efficient to call System.Collections.Generic.Dictionary2.TryAdd, which returns a Boolean value that indicates if the value was added or not. TryAdd` doesn't overwrite the key's value if the key is already present.
Cause
System.Collections.Generic.Dictionary2.Add is guarded by a System.Collections.Generic.Dictionary2.ContainsKey(`0) call.
How to fix violations
Replace a call to System.Collections.Generic.Dictionary2.ContainsKey(0) that's followed by a call to System.Collections.Generic.Dictionary2.Add with a single call to System.Collections.Generic.Dictionary2.TryAdd.
Example
void Run(IDictionary<int, string> dictionary)
{
if (!dictionary.ContainsKey(2))
{
dictionary.Add(2, "Hello World");
}
}
void Run(IDictionary<int, string> dictionary)
{
dictionary.TryAdd(2, "Hello World");
}When to suppress
It's safe to suppress this warning if performance isn't a concern and if you handle the exception that might be thrown by System.Collections.Generic.Dictionary`2.Add.