Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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 9 | As suggestion |
Dictionary<TKey,TValue>.Add is guarded by a Dictionary<TKey,TValue>.ContainsKey(TKey) call.
Both Dictionary<TKey,TValue>.ContainsKey(TKey) and Dictionary<TKey,TValue>.Add perform a lookup, which is redundant. Dictionary<TKey,TValue>.Add also throws an exception if the key is already present in the dictionary. It's more efficient to call Dictionary<TKey,TValue>.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.
Replace a call to Dictionary<TKey,TValue>.ContainsKey(TKey) that's followed by a call to Dictionary<TKey,TValue>.Add with a single call to Dictionary<TKey,TValue>.TryAdd.
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 Dictionary<TKey,TValue>.Add.
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.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register now