Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a bool value from a plethora of nullable bools?

With this code:

private bool AtLeastOnePlatypusChecked()
{
    return ((ckbx1.IsChecked) ||
            (ckbx2.IsChecked) ||
            (ckbx3.IsChecked) ||
            (ckbx4.IsChecked));
}

...I'm stopped dead in my tracks with

Operator '||' cannot be applied to operands of type 'bool?' and 'bool?

So how do I accomplish this?

like image 344
B. Clay Shannon-B. Crow Raven Avatar asked Dec 18 '12 21:12

B. Clay Shannon-B. Crow Raven


1 Answers

You can chain together |s, using the null-coalescing operator at the end:

return (ckbx1.IsChecked | cxbx2.IsChecked | cxbx3.IsChecked | cxbx4.IsChecked) ?? false;

The lifted | operator returns true if either operand is true, false if both operands are false, and null if either operand is null and the other isn't true.

It's not short-circuiting, but I don't think that'll be a problem for you in this case.

Alternatively - and more extensibly - put the checkboxes into a collection of some kind. Then you can just use:

return checkboxes.Any(cb => cb.IsChecked ?? false);
like image 77
Jon Skeet Avatar answered Oct 20 '22 16:10

Jon Skeet