Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
Dave Gordon Avatar asked Nov 19 '15 12:11

Dave Gordon


People also ask

What does != null mean?

NULL is not a value. It is literally the absence of a value. You can't "equal" NULL! The operator != does not mean "is not"; it means "is not equal to".

What does it mean return null?

null return means a return which indicates that no transaction was made by the registered person during the tax period and no amount of tax is to be paid or refunded.

What does return null mean in Java?

In Java programming, null can be assigned to any variable of a reference type (that is, a non-primitive type) to indicate that the variable does not refer to any object or array.

What does null mean programming?

If a reference points to null , it simply means that there is no value associated with it. Technically speaking, the memory location assigned to the reference contains the value 0 (all bits at zero), or any other value that denotes null in the given environment.


1 Answers

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.

like image 160
Yuval Itzchakov Avatar answered Oct 04 '22 20:10

Yuval Itzchakov