C# – Why Doesn’t Null Evaluate to False?

c++conditional-statementsnulltype-conversion

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...
}

Best Answer

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.