C#idiomatic C#
ca1864fundamentals/code-analysis/quality-rules

Code analysis

CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method

Learn about code analyzer rule CA1864 - Prefer the 'IDictionary.TryAdd(TKey, TValue)' method

CA1864 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

System.Collections.Generic.Dictionary.Add is guarded by a System.Collections.Generic.Dictionary.ContainsKey() call.

Rule description

Both System.Collections.Generic.Dictionary.ContainsKey() and System.Collections.Generic.Dictionary.Add perform a lookup, which is redundant. System.Collections.Generic.Dictionary.Add also throws an exception if the key is already present in the dictionary. It's more efficient to call System.Collections.Generic.Dictionary.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.

How to fix violations

Replace a call to System.Collections.Generic.Dictionary.ContainsKey() that's followed by a call to System.Collections.Generic.Dictionary.Add with a single call to System.Collections.Generic.Dictionary.TryAdd.

Example

The following code snippet shows a violation of CA1864:

csharp
void Run(IDictionary<int, string> dictionary)
{
    if (!dictionary.ContainsKey(2))
    {
        dictionary.Add(2, "Hello World");
    }
}
vb
Sub Run(dictionary As IDictionary(Of Integer, String))
    If Not dictionary.ContainsKey(2) Then
        dictionary.Add(2, "Hello World")
    End If
End Sub

The following code snippet fixes the violation:

csharp
void Run(IDictionary<int, string> dictionary)
{
    dictionary.TryAdd(2, "Hello World");
}
vb
Sub Run(dictionary As IDictionary(Of Integer, String))
    dictionary.TryAdd(2, "Hello World")
End Sub

When to suppress warnings

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.Add.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1864
// The code that's violating the rule is on this line.
#pragma warning restore CA1864

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1864.severity = none

For more information, see How to suppress code analysis warnings.