RSPEC-2123: Identifies target improperly by text only, reporting false positives

Details:

  • OS: Windows 11 Enterprise
  • Visual Studio 17.14.10
  • SonarQube for Visual Studio plugin version: 8.24.0.13848
  • Programming language you’re coding in: C# 12
  • Is connected mode used:
    • No

And a thorough description of the problem / question:

RSPEC-2123

Does not track the target variables in it’s analysis but rather hard text, if a model were to have a member named lineRef, then you have a local variable named lineRef you postfix increment each time you make a new one to keep track of lines easily, the rule falsely reports it’s a useless assignment as it confuses the instance member variable for the method scoped local variable for it due to name matching.

Example:

namespace SonarQube.BugReport;

using System;
using System.Collections.Generic;

internal class BugReport
{
    internal void BuildReportsExample()
    {
        int lineRef = 0;

        var erpReport = new Report();

        // Add some new report lines, each of which require their own lineRef
        erpReport.ReportLines.Add(new() { lineRef = lineRef++ }); // !!Reports S2123 here !! This is not a useless assignment
        erpReport.ReportLines.Add(new() { lineRef = lineRef });

        /// Pseudo usage
        var reportJson = System.Text.Json.JsonSerializer.Serialize(erpReport);
        Console.WriteLine($"Send our report: {reportJson}");
    }

    internal class Report
    {
        public List<ReportLine> ReportLines { get; set; } = [];
    }

    internal class ReportLine
    {
        public required int lineRef { get; set; } // If you rename this member OR the local variable of the same name, the false positive is NOT reported anymore
    }
}

Hi @RiversJohn,

This is clearly an FP, thanks for the report!
I created a ticket in our backlog to fix this in a future hardening effort.

Thanks!