Skip to content

Fix S1450 FP when field is assigned value in event handler #8239

@drieseng

Description

@drieseng

Description

When the value of a field is only changed in an event handler, then S1450 will be reported even though the field is used in different methods.

Repro steps

Compile the following code:

using System;

public sealed class Program
{
    private bool _received;

    private static void Main()
    {
        _ = new Program();
    }

    public Program()
    {
        var broker = new Broker();
        broker.Receive += Broker_Receive;

        _received = false;

        broker.Process();

        if (_received)
        {
            Console.WriteLine("OK");
        }
    }

    private void Broker_Receive(object sender, EventArgs e)
    {
        _received = true;
    }

    private sealed class Broker
    {
        public event EventHandler Receive;

        public Broker()
        {
        }

        public void Process()
        {
            Receive?.Invoke(this, EventArgs.Empty);
        }
    }
}

Expected behavior

S1450 is not reported.

Actual behavior

error S1450: Remove the field '_received' and declare it as a local variable in the relevant methods. (https://rules.sonarsource.com/csharp/RSPEC-1450)

If you run the compiled assembly, you'll see that "OK" is written to standard output hereby showing that the value of the _received field changed (by the event handler) between the moment it was assigned the value false and the moment we checked whether it was true.

Known workarounds

Disable the rule for the '_received' field.

Related information

  • C#/VB.NET Plugins version: 9.12.0.78982
  • Visual Studio version: 17.8.0 Preview 2.0
  • MSBuild / dotnet version: 7.0.402
  • Operating System: Windows 10

Metadata

Metadata

Labels

False PositiveRule IS triggered when it shouldn't be.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions