Hello guys,
I am using SonarCloud and I found an issue while analyzing c# code which might be an FP. The rule affected is S2259.
I reproduced it in a simpler way, so you could understand what happend. I declared a List which is not possible to get null (as you can see there is no operator in the declaration which would make the List nullable). I did not create a new one with a new-Operator, instead I assigned a List which is already existing to the new Variable.
I think your Analyzer saw the expression in the if-statement and that is why the bug occurs, but actually that shouldnât make any difference. I even tried just for fun to assign the value null to the list later on, but the compiler doesnât allow that.
The âbugâ occurs in the foreach-loop. It says that the not-nullable List is null on at least one execution path. But I donât think that this is possible in this szenario.
Have fun with the code example
public static long Test()
{
long sum = 0;
long[] array = new[] { 1L, 2L, 3L };
List<long> test = array.ToList();
if (test?.Count == 0)
{
// Do something
}
foreach (long number in test) // Reported Bug: 'test' is null on at least one execution path.
{
sum += number;
}
return sum;
}
Reported Bug in the foreach-loop: âtestâ is null on at least one execution path.