SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
798 stars 229 forks source link

Fix S2583 FP: List is filled in local function, then checking its Count is > 0 #9671

Open nalka0 opened 1 month ago

nalka0 commented 1 month ago

Description

There's a false positive for S2583 with the below snippet

Repro steps

public static void S2583()
{
    List<int> list = new();
    foreach (var item in Enumerable.Range(0, 5))
    {
        if (item % 2 == 0)
        {
            LocalFunction(item);
        }

        void LocalFunction(int added)
        {
            list.Add(added);
        }
    }

    if (list.Count > 0) // S2583 false positive
    {
        Console.WriteLine("This code is reachable");
    }
}

Expected behavior

No occurence of S2583

Actual behavior

S2583 is raised on if (list.Count > 0)

Known workarounds

None

Related information

CristianAmbrosini commented 1 month ago

Hi @nalka0!

I confirm this as a FP. Currently, we do not track collections filled within local methods. I'll add a reproducer to track them in our repo. Thanks for the feedback!