sonar-dotnet
sonar-dotnet copied to clipboard
Fix S2583 FP: Wrong evaluation in switch-case assignment
Description
Please provide a succinct description of your issue. Also please provide the rule ID (e.g. S1234)
Repro steps
private static void Foo()
{
string? one = null;
string? two = null;
var values = new List<string>
{
"one",
"two"
};
foreach (var value in values)
{
switch (value)
{
case "one":
one = value;
break;
case "two":
two = value;
break;
}
}
if (string.IsNullOrEmpty(one))
{
Console.WriteLine("one");
return;
}
// Change this condition so that it does not always evaluate to 'True'. Some code paths are unreachable.
if (string.IsNullOrEmpty(two))
{
Console.WriteLine("two");
}
}
Expected behavior
No false-positive as variable two can be null if it doesn't hit the switch case.
Actual behavior
A false-positive is reported.
Known workarounds
Instead of declaring the two variables as string?, use string.Empty.
var one = string.Empty;
var two = string.Empty;
Related information
SonarQube connected mode with VS2022
Hello @4865783a5d, I cannot reproduce the issue. Which version of the analyzer are you using? Anyway, if you still have the issue, there is a good chance it is connected to https://github.com/SonarSource/sonar-dotnet/issues/8474 which will be fixed in 9.20.