nullable bool in if() statement - checks required?

别来无恙 提交于 2021-02-19 01:08:52

问题


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! :))


回答1:


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)
{

}



回答2:


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.




回答3:


You can simplify this by checking for the value to be true, like this:

bool IsTrue(bool? value)
{
   return value == true;
}

This will work for nulls as well, returning false.

I prefer using this check "inline", without an additional function, because it is short and clean:

if(foo == true){
   doSomething()
}



回答4:


since this doesnt compile

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        bool? test = null;
        if (test)
        {
            Console.WriteLine("ok");
        }
        Console.ReadKey();
    }
}
}

i would do something like

class Program
{
    static void Main(string[] args)
    {
        bool? test = null;
        if (test ?? false)
        {
            Console.WriteLine("ok");
        }
        Console.ReadKey();
    }
}

but there is a million way of doing this so pick one and stick with it :-)




回答5:


You will have to check if the bool has value first.

I would do as you first proposed:

value.HasValue && value.Value

As it is most clear to people reading the code.



来源:https://stackoverflow.com/questions/20197275/nullable-bool-in-if-statement-checks-required

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!