Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper bug? Incorrect "expression is always true"

I believe I have found a bug in ReSharper. Suppose I have code as follows:

int[] someArray = new int[10];
while (someArray  != null)
{
     //perhaps some other usage of someArray here, but not assigning it.
     SomeMethod(ref someArray );
}

If the local variable someArray is not assigned to null in its scope, then the statement someArray != null would always be true. But that isn't the case when that variable is given as ref-parameter to another method, since it could get assigned to null in that method. Then ReSharper incorrectly assumes that someArray != null is still always true.

I thought I'd share this information, because I'm unsure what I should do with this. Firstly I'd like someone to verify this bug, and afterwards send it to JetBrains?

like image 209
JBSnorro Avatar asked Dec 16 '22 15:12

JBSnorro


2 Answers

Hm, apparently the static analysis of ReSharper is smarter than me.... The code in which I correctly get the "expression is always true" warning is:

int[] someArray = new int[10];
while (someArray != null)
{
    Foo(ref someArray);
    someArray.Bar();
}

I get the warning that someArray != null is redundant, so I thought ReSharper misinterpreted the ref parameter, since someArray can in fact be assigned to null. But that is not the reason why the warning is correct. Then a subtle fact plays a role: that someArray is null would mean that the method invocation of Bar would throw a NullReferenceException, and with that alter the control flow such that the start of the while loop isn't reached. So even when someArray is assigned to null in Foo, the warning is correct.

My mistake, and thank you all for your effort.

like image 136
JBSnorro Avatar answered Dec 29 '22 12:12

JBSnorro


Try to change this loop to do-while and check what ReSharper marks it in this situation. Is it still always true? But on first loop, it is really "always true", so ReSharper evaluates it correctly (it is static analysis).

like image 43
Marek Kwiendacz Avatar answered Dec 29 '22 10:12

Marek Kwiendacz