C# false positive on foreach with switch

Hi, We got error S2583 on our sonar cloud on code that can be reached. I reproduced this scenario on small repo, here’s a code:

 public void CheckForeachNull(List<Monkey> infoList)
 {
     Monkey insurNew = null;
     Monkey insur = null;
     if (infoList == null)
     {
         infoList = new List<Monkey>();
     }
     
     foreach (var rei in infoList)
     {
         switch (rei.Type)
         {
             case (int)Gender.Male:
                 insur = new Monkey() { Type = 1};
                 break;
             case (int)Gender.Female:
                 insurNew = new Monkey() { Type = 2 };
                 break;
         }
     }

     if (insur != null && insurNew != null)
     {
         Console.WriteLine(insur.Name);
     }
 }

public class Monkey
{
    public string Name { get; set; }
    public int Type { get; set; }
}

public enum Gender
{
    Male = 1,
    Female = 2
}

image

It can be reached when you invoke method CheckForeachNull with parameter List with at least two object, where one is Type 1 and second is Type 2.

Please let me know, how we can fix this issue, right now I can’t merge my PR, because sonar is blocking it.

Hello @Lukasz_Granica, and thank you for reporting this.

This is a false positive from a known limitation to our symbolic execution engine.
The engine explores loops only two times, and it does not get the chance to learn that insurNew can also not be null at the same time as insur; so, as a result, an issue is raised.

We already have similar issues to our backlog (for example see here, here and here), where you can read more information.

To move on with your PR, I suggest that you mark this issue as a false positive, and you can add a link to this post as an explanation if needed.