Possible False Positive affecting a non-nullable List in C# - S2259

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 :slight_smile:

       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.

Similar to what @mloh22 reported. I’m getting the same error here. Any updates on this one?

        public static void DoSomething()
        {
            var list = GetList();
            if (list is null)
                ThrowException();

            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }

        private static IEnumerable<string> GetList()
        {
            return new List<string> {"123"};
        }

        private static void ThrowException()
        {
            throw new ArgumentException("Some message");
        }

if I update the if condition to this:

if (list is null)
{
    throw new ArgumentException("Some message");
}

the warning goes away

Hello @mloh22

Thanks for reporting this issue, I can confirm it as a FP.
I created the following issue, where you can track the progress.

Hello @yoliva

Unfortunately your case has a different root cause. We currently do not support inteprocedural analysis for this rule and that is the reason why an issue is raised in your case.

Hi @Caba_Sagi, what do you recommend for this? We tagged the issue as false positive for now. Additionally, do you have in your roadmap to support this?

Thanks

For now you did the right thing, you should tag it as a false positive.
Unfortunately inteprocedural analysis is not yet part of our roadmap even though we would really like to have support for it.

1 Like