A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1864 below:

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

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 Cause

Dictionary<TKey,TValue>.Add is guarded by a Dictionary<TKey,TValue>.ContainsKey(TKey) call.

Rule description

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.

How to fix violations

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.

Example

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
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 Dictionary<TKey,TValue>.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.

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4