Environment: Sonar C# Analyzer version 8.19.0.28253 in Visual Studio 2019 Professional version 16.11.2.
Given the following example code structure, where I look for a value in one of two different dictionaries based on some input parameters (that define the key, so key1
is for dictionary1
and key2
is for dictionary2
):
public static string TestFunction(string key1, string key2)
{
var dictionary1 = new Dictionary<string, string>();
var dictionary2 = new Dictionary<string, string>();
string value;
if (string.IsNullOrEmpty(key1)) dictionary2.TryGetValue(key2, out value);
else dictionary1.TryGetValue(key1, out value);
return value;
}
The S3240 warning suggests that the conditional expression should be simplified and the following code is suggested:
dictionary2.TryGetValue(string.IsNullOrEmpty(key1) ? key2 : key1, out value);
The issue is that this expression is not the same logic as the one it replaces, because it will use both keys on dictionary2
(so dictionary1
is now unused).