Best way to check for nullable bool in a condition

2019-01-13 03:03发布

I was wondering what was the most clean and understandable syntax for doing condition checks on nullable bools.

Is the following good or bad coding style? Is there a way to express the condition better/more cleanly?

bool? nullableBool = true;
if (nullableBool ?? false) { ... }
else { ... }

especially the if (nullableBool ?? false) part. I don't like the if (x.HasValue && x.Value) style ...

(not sure whether the question has been asked before ... couldn't find something similar with the search)

12条回答
太酷不给撩
2楼-- · 2019-01-13 03:10

Actually I think that (nullableBool ?? false) is a legitimate option especially when you are trying to evaluate a nullable bool in linq.

For example:
array.Select(v => v.nullableBool ?? false)
(from v in array where v.nullableBool ?? false)

Is cleaner in my opinion as opposed to:
array.Select(v => v.nullableBool.HasValue ? v.nullableBool.Value : false)
(from v in array where v.nullableBool.HasValue ? v.nullableBool.Value : false)

查看更多
对你真心纯属浪费
3楼-- · 2019-01-13 03:12

If you only want to test for true against null/false, One I've just used and reads quite well is

bool? someCondition = null
if (someCondition.Equals(true))
...
查看更多
The star\"
4楼-- · 2019-01-13 03:13

You may not like it, but personally I find

if (x.HasValue && x.Value)

the most readable. It makes it clear you are working with a nullable type and it makes it clear you are first checking whether the nullable type has a value before acting on it conditionally.

If you take your version and replace the variable with x also it reads:

if (x ?? false)

Is that as clear? Is it obvious x is a nullable type? I'll let you decide.

查看更多
趁早两清
5楼-- · 2019-01-13 03:19

Given enum

public enum PublishMode { Edit, View }

you can do it like here

 void MyMethod(PublishMode? mode)
    {
       var publishMode = mode ?? PublishMode.Edit;

//or
       if (mode?? PublishMode.Edit == someValue)
       ....
    }
查看更多
三岁会撩人
6楼-- · 2019-01-13 03:21

If you want to treat a null as false, then I would say that the most succinct way to do that is to use the null coalesce operator (??), as you describe:

if (nullableBool ?? false) { ... }
查看更多
劫难
7楼-- · 2019-01-13 03:23

I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null

Or if you want more options...

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null

(nullableBool == true) will never return true if the bool? is null :P

查看更多
登录 后发表回答