title | description | ms.date | f1_keywords | helpviewer_keywords | dev_langs | |||||
---|---|---|---|---|---|---|---|---|---|---|
CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method |
Learn about code analyzer rule CA1864 - Prefer the 'IDictionary.TryAdd(TKey, TValue)' method |
06/30/2023 |
|
|
|
Property | Value |
---|---|
Rule ID | CA1864 |
Title | Prefer the 'IDictionary.TryAdd(TKey, TValue)' method |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As suggestion |
xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType is guarded by a xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType call.
Both xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType and xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType perform a lookup, which is redundant. xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType also throws an exception if the key is already present in the dictionary. It's more efficient to call xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType, 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.
Replace a call to xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType that's followed by a call to xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType with a single call to xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType.
The following code snippet shows a violation of CA1864:
void Run(IDictionary<int, string> dictionary)
{
if(!dictionary.ContainsKey(2)) {
dictionary.Add(2, "Hello World");
}
}
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:
void Run(IDictionary<int, string> dictionary)
{
dictionary.TryAdd(2, "Hello World");
}
Sub Run(dictionary As IDictionary(Of Integer, String))
dictionary.TryAdd(2, "Hello World")
End Sub
It's safe to suppress this warning if performance isn't a concern and if you handle the exception that might be thrown by xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType.
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#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.
[*.{cs,vb}]
dotnet_diagnostic.CA1864.severity = none
For more information, see How to suppress code analysis warnings.