Null-conditional boolean in if statement
Asked Answered
A

4

8

I have an event which returns a boolean. To make sure the event is only fired if anyone is listening, i call it using the null-conditional operator (questionmark). However, this means that I have to add the null-conditional operator to the returned boolean as well. And that means that I cannot figure out how to use it in an if-statement afterwards. Does anyone knows how to handle this?

switch (someInt) 
{
    case 1:
        // Validate if the form is filled correctly.
        // The event returns true if that is the case.
        bool? isValid = ValidateStuff?.Invoke();

        if (isValid)
            // If passed validation go to next step in form 
            GoToNextStep?.Invoke();
        break; 

    // There are more cases, but you get the point
    (...)
}
Agace answered 13/6, 2017 at 9:34 Comment(0)
M
14

You could use

if (isValid.GetValueOrDefault())

which will give false if isValid is null.

or use the ?? operator

if (isValid ?? false)

which returns the value of the left operand if it is not null and the value of the right operand otherwise. So basically a shorthand for

if (isValid == null ? false : isValid)
Martino answered 13/6, 2017 at 9:38 Comment(0)
P
3

The problem is that in case of Nullable bool? you have three-valued logic: true, false and null and thus you have to put explicitly if null should be treated as true, e.g.:

   if (isValid != false)     // either true or null
     GoToNextStep?.Invoke();

or null shall be considered as false:

   if (isValid == true)      // only true
     GoToNextStep?.Invoke(); 
Placida answered 13/6, 2017 at 9:54 Comment(0)
J
2

You can use this:

if (isValid.HasValue && isValid.Value)
Jerome answered 13/6, 2017 at 9:41 Comment(0)
O
1

One option would be to test wether isValid has a value:

if (isValid.HasValue && (bool)isValid)

Another option is to give isValid a default value when nobody is listening to your event. This can be done with the null coalescing operator:

bool isValid = ValidateStuff?.Invoke() ?? true;   // assume it is valid when nobody listens
Oma answered 13/6, 2017 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.