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! :))
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)
{
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With