CA1854: Prefer the IDictionary.TryGetValue(TKey, out TValue)
method
Property | Value |
---|---|
Rule ID | CA1854 |
Title | Prefer the IDictionary.TryGetValue(TKey, out TValue) method |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As suggestion |
Cause
An IDictionary
element access that's guarded by an IDictionary.ContainsKey
check.
Rule description
When an element of an IDictionary
is accessed, the indexer implementation checks for a null value by calling the IDictionary.ContainsKey
method. If you also call IDictionary.ContainsKey
in an if
clause to guard a value lookup, two lookups are performed when only one is needed.
How to fix violations
Replace the IDictionary.ContainsKey
invocation and element access with a call to the IDictionary.TryGetValue
method.
Violation:
public string? GetValue(string key)
{
if (_dictionary.ContainsKey(key))
{
return _dictionary[key];
}
return null;
}
Public Function GetValue(key As String) As String
If _dictionary.ContainsKey(key) Then
Return _dictionary(key)
End If
Return Nothing
End Function
Fix:
public string? GetValue(string key)
{
if (_dictionary.TryGetValue(key, out string? value))
{
return value;
}
return null;
}
Public Function GetValue(key As String) As String
Dim value as String
If _dictionary.TryGetValue(key, value) Then
Return value
End If
Return Nothing
End Function
When to suppress warnings
It's safe to suppress this warning if you're using a custom implementation of IDictionary
that avoids a value lookup when performing the IDictionary.ContainsKey
check.
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 CA1854
// The code that's violating the rule is on this line.
#pragma warning restore CA1854
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1854.severity = none
For more information, see How to suppress code analysis warnings.