Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand why ReSharper told me expression is always false

I have a conditional I'm writing that's checking three things.

if(LoggedInMembershipUser == null || obj == null || boolVal)

In this case, "LoggedInMembershipUser" is just the Membership.GetUser(), "obj" is some random business object, and "boolVal" is obviously a boolean. When I write the statement as above, ReSharper tells me that the boolVal portion of the statement is always false. But when I put boolVal at the beginning as below, I don't get that notice.

if(boolVal|| LoggedInMembershipUser == null || obj == null)

Why would the first one always be false but the second one not?

EDIT: This is in the row data bind of a grid view. The grid is displaying results from two objects with the same base class, so "obj" will have a value if it's one of the object types but not the other. boolVal is an indicator for which type of object it is, so now that I think about it, I guess if obj is null then boolVal will always be true. Was ReSharper realizing that somehow? Oh I bet it was because looking at my code above the line I have:

if (!uploaded){
    var obj = GetObjectLogic();
}

Ok thanks for the help comments. I guess this can be voted to be deleted or whatever.

like image 917
William Avatar asked Jan 24 '13 20:01

William


2 Answers

Without more of the method it is hard to know for sure, but it sure looks ike the following:

ReSharper has determined that the only way that boolVal can be true is if at least one of LoggedInMembershipUser or obj is null. That first if never reaches the boolval portion unless both are not null. Thus at the point where boolVal is evaluated it must be false.

If you reorder the conditions, then that logic no longer holds. ReSharper could potentially analyze that expression, determine that all parts are fast and side effect free, and notice that boolVal is not necessary in the second case too, but that analysis is somewhat harder and apparently has not been written.

like image 124
Kevin Cathcart Avatar answered Nov 15 '22 03:11

Kevin Cathcart


Every time I've investigated an unexpected Expression is always true|false scenario with ReSharper, the tool has proved smarter than me. For example, ReSharper is aware of inheritance trees; in this code block:

void doSomething(Object obj)
{
    if(obj is StreamReader || obj is TextReader)
        foo();
}

...ReSharper will mark (obj is TextReader) as Expression is always false, because the (obj is StreamReader) code branch will already have captured any TextReader objects and jumped to foo(), short-circuiting any further evaluation.

like image 27
Paul Smith Avatar answered Nov 15 '22 03:11

Paul Smith