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
788 stars 227 forks source link

Fix S1450 FP: private field is used in several methods #9672

Open nalka0 opened 1 month ago

nalka0 commented 1 month ago

Description

S1450 is raised on the following snippet despite foundMultiple being used on both methods

Repro steps

private class LookForSinglePropertyAccessExpressionVisitor : ExpressionVisitor
{
    private PropertyInfo foundProperty;

    private bool foundMultiple; // S1450 FP here (but it's used on both methods)

    public PropertyInfo GetUsedProperty(Expression expression)
    {
        foundProperty = null;
        foundMultiple = false;
        Visit(expression);
        if (foundMultiple)
        {
            throw new ArgumentException($"{expression} contains more than one property access", nameof(expression));
        }

        return foundProperty ?? throw new ArgumentException($"{expression} contains no property access", nameof(expression));
    }

    protected override Expression VisitMember(MemberExpression node)
    {
        if (node.Member is PropertyInfo prop)
        {
            if (foundProperty != null)
            {
                foundMultiple = true;
            }

            foundProperty = prop;
        }

        return base.VisitMember(node);
    }
}

Expected behavior

No occurrence of S1450 in the above snippet

Actual behavior

S1450 is raised on the above snippet despite foundMultiple being used on both methods

Known workarounds

None

Related information

CristianAmbrosini commented 1 month ago

Hi @nalka0!

It's a FP, indeed. I discovered that we already have a reproducer for this on our repo. I'll make sure to add a link to this since it seems we don't have a ticket for it yet.

Thanks,