S1172 Gives false positives when parameter is used in switch or switch expressio in a local function

I have a few S1172 false positives in my C# code that look something like this:

private static string Test(string currentUnit)
{
    return GetLongUnit();

    string GetLongUnit()
    {
        return currentUnit switch
        {
            "M" => "Meters",
            _ => "Yards"
        };
    }
}

In this case the currentUnit parameter is marked as not being used, although to me it appears it is.

Obviously if I change the code to something like this:

private static string Test(string currentUnit)
{
    return GetLongUnit(currentUnit);

    string GetLongUnit(string unit)
    {
        return unit switch
        {
            "M" => "Meters",
            _ => "Yards"
        };
    }
}

It makes the analyzer happy.

It appears to me that this only happens with the parameter used in a switch expression or switch case. At least I haven’t found any other case where it happens. As soon as I use currentUnit in a different way in the local function the analyzer becomes happy and does not report the parameter not being used.

This issue seems to start occurring after we updated SonarAnalyzer.CSharp to 10.4.0.108396

1 Like

I agree this is a false positive. It turns out that local (non-static) methods are not taken into account here.

Hello @Tomasz

I confirm this False Positive. I added a re-producer to our code base and created an internal ticket to track our work on it.

1 Like

Thank you Martin and Corniel!

Looking forward to a fix getting out :slight_smile: