Both SonarQube 8 and 9 (Community Edition) reports a false positive issue on this code below.
It says Change this condition so that it does not always evaluate to ‘false’; some subsequent code is never executed and highlights the part text.Length == 3
in red and the body of the subsequent elseif block.
I’ve also asked the same question on StackOverflow and the person who answered also thinks it is a bug with SonarQube and not with my code.
using System;
using System.Collections.Generic;
namespace Console1;
public static class Program
{
public static void Main()
{
string[] test = { "1", "22", "333", "1", "22", "4444" };
SonarPleaseWhy(test);
}
public static void SonarPleaseWhy(IList<string> texts)
{
bool firstItemAdded = false;
bool otherItemAdded = false;
foreach (var text in texts)
{
if (!firstItemAdded && text.Length == 1)
{
firstItemAdded = true;
}
else if (firstItemAdded && text.Length == 2)
{
otherItemAdded = true;
}
else if (otherItemAdded && text.Length == 3)
{
Console.WriteLine($"It entered the 'if' with text {text}");
firstItemAdded = false;
otherItemAdded = false;
}
else
{
firstItemAdded = false;
otherItemAdded = false;
}
}
}
}