Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't null evaluate to false?

Tags:

What is the reason null doesn't evaluate to false in conditionals?

I first thought about assignments to avoid the bug of using = instead of ==, but this could easily be disallowed by the compiler.

if (someClass = someValue) // cannot convert someClass to bool. Ok, nice  if (someClass) // Cannot convert someClass to bool. Why?  if (someClass != null) // More readable? 

I think it's fairly reasonable to assume that null means false. There are other languages that use this too, and I've not had a bug because of it.

Edit: And I'm of course referring to reference types.

A good comment by Daniel Earwicker on the assignment bug... This compiles without a warning because it evaluates to bool:

bool bool1 = false, bool2 = true; if (bool1 = bool2) {     // oops... false == true, and bool1 became true... } 
like image 941
simendsjo Avatar asked Jul 07 '10 17:07

simendsjo


People also ask

Does null evaluate to false?

Comparing any variable with NULL will always evaluate to FALSE, regardless if it's value, unless IS NULL or IS NOT NULL is used. Violating this rule will affect the functionality of the code. The severity is critical which means that the code will not function correctly.

Why is null not false?

The way you typically represent a “missing” or “invalid” value in C# is to use the “null” value of the type. Every reference type has a “null” value; that is, the reference that does not actually refer to anything.

Why null == false is false?

Answer : There no relative aspect between null and boolean. The value null is a literal (not a property of the global object like undefined can be). In APIs, null is often retrieved in place where an object can be expected but no object is relevant.

Does null evaluate to TRUE?

This means that for GROUP BY clause NULL = NULL does not evaluate to NULL, as in 3VL, but it evaluate to TRUE. Whether a sort key value that is NULL is considered greater or less than a non-NULL value is implementation-defined, but... ... There are SQL products that do it either way.


1 Answers

It's a specific design feature in the C# language: if statements accept only a bool.

IIRC this is for safety: specifically, so that your first if (someClass = someValue) fails to compile.

Edit: One benefit is that it makes the if (42 == i) convention ("yoda comparisons") unnecessary.

like image 105
Tim Robinson Avatar answered Sep 28 '22 20:09

Tim Robinson