Dave Gordon
Dave Gordon

Reputation: 1835

What does Return myVar != null actually mean?

Resharper is a great tool, but it sometimes confuses me as to what the suggested code really means. I have this code:

private bool DoesUserExists()
{
    var user = De.Users.FirstOrDefault(u => u.Username == CurrentUser.Username);
    return user != null;
}

I originally had :

if(user == null)
    return false;
else
    return true;

But Resharper suggested the top code. However, that looks to me to be saying return user if it is not null. But the method only accepts a bool return and not a class.

So what does return user != null actually return when it is null and when it is not?

Upvotes: 6

Views: 4316

Answers (2)

Carl Manaster
Carl Manaster

Reputation: 40356

Not sure I'm adding any value here, @Yuval's answer is correct and clear, but maybe it helps to see it this way.

You are thinking of parsing the code something like this:

(return user) (!= null)

That is, you see "return user" and wonder what the rest of the line is doing there. But return doesn't work that way. It evaluates the rest of the line, and returns that. It's more like

(return) (everything else)

or, in the specific case

(return) (user != null)

Where return gets executed last.

It is much like operator precedence, where 3+5*2 must be evaluated as 3+10 instead of 8*2, because * has higher precedence (must be evaluated first) than +. return has the lowest precedence of all.

If you learn to read and write code with this in mind, you will find yourself appreciating the refactored code.

Upvotes: 4

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

So what does return user != null actually return when it is null and when it is not

It simply evaluates the expression. If user is null it returns false and if user isn't null, it returns true.

Think of this as if you were assigning the result of the comparison to a local variable, and only then returning it:

bool isNotNull = user != null;
return isNotNull;

Or:

bool isNull = user == null;
return !isNull;

isNotNull would be true only iff the user variable is not null.

Semantically, it is identical to your if-else statement.

Upvotes: 9

Related Questions