sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

Fix S2583 FP: Wrong evaluation in switch-case assignment

Open 4865783a5d opened this issue 1 year ago • 1 comments

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

4865783a5d avatar Feb 12 '24 15:02 4865783a5d

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.

Tim-Pohlmann avatar Feb 19 '24 10:02 Tim-Pohlmann