sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

S1450 FP field to local variable

Open Thieum opened this issue 5 years ago • 1 comments

Description

Combining a field with event handlers / methods leads to S1450 false positive. Positionning inside the event handlers also changes the behavior of the result.

Repro steps

Here is a minimal program that reproduces the issue:

using System;
using System.Threading;
using System.Timers;

namespace ConsoleApp16
{

    sealed class TimerTest : IDisposable
    {

        readonly System.Timers.Timer _testClosingTimer = new System.Timers.Timer(300);
        bool _testIsClosed;

        public TimerTest() => Testing += Test;

        public event EventHandler Testing;

        public void Dispose() => _testClosingTimer.Dispose();

        public void Tester() => Testing?.Invoke(this, EventArgs.Empty);

        void Test(object _, EventArgs _2) // this can be a method, the FP will be present too
        {

            _testClosingTimer.AutoReset = false;
            _testClosingTimer.Elapsed += TestClosingTimerElapsed;
            _testIsClosed = false;
            _testClosingTimer.Start();
            while (!_testIsClosed)
            {
                Thread.Sleep(1);
            }
        }

        void TestClosingTimerElapsed(object sender, ElapsedEventArgs e) => _testIsClosed = true; // this can be a method, the FP will be present too

    }

    static class Program
    {
        static void Main()
        {
            using (var test = new TimerTest())
            {
                test.Tester();
            }
        }


    }
}

Expected behavior

S1450 shouldn't pop on the _testIsClosed field as it is used in multiple methods.

Actual behavior

S1450 pops on the _testIsClosed field.

Known workarounds

moving the assignation

_testIsClosed = false;

to the top of the event handler Test makes the rule works again as intended. it seems the position of the assignation is the relevant issue here, as swapping to method or event handler, private or public doesn't change the behavior.

Related information

  • SonarLint for Visual Studio 4.10.0.9867 / Sonar C# 7.14
  • Visual Studio Enterprise 2019 16.1.3

Thieum avatar Jun 21 '19 18:06 Thieum

This will also reproduce the false positive:

public class MethodUpdateTest
{
    private int value = 0;

    private void Reset() => value = 0;

    public void TestMethod()
    {
        value = 20;

        while (value != 0)
        {
            Reset();
        }
    }
}

This is a duplicate of #8239

Tim-Pohlmann avatar Apr 10 '24 07:04 Tim-Pohlmann