Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nullable bool in if() statement - checks required?

Tags:

c#

nullable

I just came across this in a coworkers code. He has a nullable bool type that he compares like this:

//foo has no value here and evaluated to false
if(foo==true)
{
    doSomething();
}

Typically, the way I check a nullable boolean is something like this:

bool IsTrue(bool? value)
{
   return value.HasValue && value.Value;
}

if(IsTrue(foo)){
   doSomething()
}

Edit: I ran through both methods and they both appear work the same way. I'm asking which one is the correct way and if the extra checks are necessary??

Now I am questioning both myself and my coworkers code. Is there any point in me doing this extra check here? Or can I safely do it the first way?

Thanks (and yes I did search for this! :))

like image 741
dferraro Avatar asked Nov 25 '13 15:11

dferraro


2 Answers

Actually I don't recommend you to treat null as false. Either use non-nullable boolean, or explicitly handle null value. One more option to do that:

if (foo ?? false)
{

}
like image 129
Sergey Berezovskiy Avatar answered Nov 10 '22 17:11

Sergey Berezovskiy


I'd use this.

bool IsTrue(bool? value)
{
   return value.GetValueOrDefault();
}

This will return false when null or false and true only when it has a value and true.

Note: You cannot use bool? in if statement, as if statement requires anything which is implicitly convertible to Boolean. where as bool? is not convertible to boolean, so compiler will complain.

like image 30
Sriram Sakthivel Avatar answered Nov 10 '22 19:11

Sriram Sakthivel