-3

Why can I compare nullable boolean values in C# like this:

bool? test = true;
if (test==true)
   //do somethign

but not like this:

bool? test = true;
if (test)
   //do somethign
Jan Hommes
  • 5,122
  • 4
  • 33
  • 45

1 Answers1

0

The if statement in C# can only take a bool parameter.

Nullable<bool> is not the same as bool, and null is neither true nor false.

If you know your bool? has a value, you can use:

if (test.Value)
    //do something
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • 2
    And if you _don't_ know if it has a value, use `test.GetValueOrDefault()`: if it has a value, it will use it. If it doesn't, it will use `false`. – Chris Sinclair Mar 30 '13 at 12:51