SonarLint false positive of S2589 on if-else-if-else-if construct with two booleans

In the following C# routine, in the last else-if, Rider Sonarlint 10.3.0.77475 incorrectly marks the !ctrlPressed with S2589.

The two booleans have four logical combinations. The last else-if branch is selected if and only if both booleans are false.

        private void UpdateVertexSelection(Coordinate vertex, bool shiftPressed, bool ctrlPressed)
        {
            if (shiftPressed && !ctrlPressed)
            {
                AddVertexToSelection(vertex);
            }
            else if (!shiftPressed && ctrlPressed)
            {
                ToggleVertexSelection(vertex);
            }
            else if (!shiftPressed && !ctrlPressed)
            {
                selectedVertices.Clear();
                selectedVertices.Add(vertex);
            }
        }

Hello @andreasbuykx thanks for the report!

The last check for !ctrlPressed is indeed superfluous because !shiftPressed && ctrlPressed was checked before. If shiftPressed is false at this point, ctrlPressed must be false as well. This code is equivalent:

private void UpdateVertexSelection(Coordinate vertex, bool shiftPressed, bool ctrlPressed)
{
    if (shiftPressed && !ctrlPressed)
    {
        AddVertexToSelection(vertex);
    }
    else if (!shiftPressed)
    {
        if (ctrlPressed)
        {
            ToggleVertexSelection(vertex);
        }
        else
        {
            selectedVertices.Clear();
            selectedVertices.Add(vertex);
        }
    }
}

And just for fun a rewrite using tuple pattern:

private void UpdateVertexSelection(Coordinate vertex, bool shiftPressed, bool ctrlPressed)
{
    switch (shiftPressed, ctrlPressed)
    {
        case (true, false):
            AddVertexToSelection(vertex);
            break;
        case (false, true):
            ToggleVertexSelection(vertex);
            break;
        case (false, _):
            selectedVertices.Clear();
            selectedVertices.Add(vertex);
            break;
    }
}

Oh :man_facepalming:. I was really not thinking straight at the time.

That tuple pattern looks elegant BTW.

Can I delete the post , or mark it as not-a-bug?

Don’t worry about it; marking it as solved is sufficient. Feedback is essential for us, so please don’t hesitate to report your findings in the future!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.