Sonar C# Analyzer ( suggests incorrect change for RSPEC-3240

Environment: Sonar C# Analyzer version 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).

Hello @BenedekFarkas and welcome to our community.
Thanks for reporting this problem. I created the following issue, where you can track the progress.

Best regards,

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.