Alex Rivera | Logout

Why do nullable bools not allow if(nullable) but do allow if(nullable == true)?

Asked 2009-01-15T16:17:33.653
36

This code compiles:

private static void Main(string[] args)
{
    bool? fred = true;

    if (fred == true)
        Console.WriteLine("fred is true");
    else if (fred == false)
         Console.WriteLine("fred is false");
    else Console.WriteLine("fred is null");
}

This code does not compile.

private static void Main(string[] args)
{
    bool? fred = true;

    if (fred)
        Console.WriteLine("fred is true");
    else if (!fred)
         Console.WriteLine("fred is false");
    else Console.WriteLine("fred is null");
}

I thought if(booleanExpression == true) was supposed to be a redundancy. Why isn't it in this case?

Edit
Report

3 Answers

3

The statement Nullable<bool> == true is implicitly checking Nullable<bool> == (Nullable<bool>)true.

Note that Nullable<bool> itself is not a boolean. It is a wrapper for a boolean that can also be set to null.

answered 2009-01-15T16:24:10.737
0

If you cast fred to boolean, it will compile :

  if (( bool )fred )
      (...)

I think that when you compare bool? to bool, the compiler make an implicite cast, do the comparison, and then return true or false. Result : the expression evaluate to a bool.

When you don't compare bool? to something, the expression evaluate to a bool?, who's illegal there.

answered 2009-01-15T16:26:32.463
0

Technically the bare conditional test doesn't require an implicit conversion to bool if you have an implementation of the true operator.

bool? nullableBool = null;
SqlBoolean sqlBoolean = SqlBoolean.Null;
bool plainBool = sqlBoolean; // won't compile, no implicit conversion
if (sqlBoolean) { } // will compile, SqlBoolean implements true operator

The original question is looking for a SQL style implementation of nulls where null is treated more like an unknown, while the Nullable implementation is more like adding null as an extra possible value. For example compare:

if (((int?)null) != 0) { } //block will execute since null is "different" from 0
if (SqlInt32.Null != 0) { }  // block won't execute since "unknown" might have value 0

The more database like behavior is available from the types in System.Data.SqlTypes

answered 2009-07-29T20:48:32.853

Your Answer