Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# bool operations to detect any false return

Tags:

c#

boolean

I'd like to write something like the following....

bool hasAnyInvalid = false;
hasAnyInvalid |= IsValidType1(...);
hasAnyInvalid |= IsValidType2(...);
hasAnyInvalid |= IsValidType3(...);
hasAnyInvalid |= IsValidType4(...);

if (hasAnyInvalid){ return false; }

As far as I can tell, the above will fail because true | true is false.

How can I use one boolean variable to test multiple functions for a false?

I need to evaluate each of the IsValidType functions. So I can't short-circuit it out.

Basically, I want a logic gate that once it goes true, it stays true. I seem to recall doing this in the past in C++ with HRESULT returns, but we may have simply been adding up the integer value of the severity.

I'm open to other ways of solving this.

EDIT: I poorly phrased this question, and included a few logical snafus ( I meant to write this as an XOR ). I'm going to leave my original question above because people specifically commented about it, and I hate to alter history.

like image 452
ElMalakai Avatar asked Dec 21 '22 03:12

ElMalakai


2 Answers

If you want to detect a single false, you need to use an &, not an |:

bool allValid = true; // Start it with "true"
allValid &= IsValidType1(...); // The first "false" will make "allValid" false
allValid &= IsValidType2(...);
allValid &= IsValidType3(...);
allValid &= IsValidType4(...);
if (!allValid) { // Invert "allValid" before returning
    return false;
}
like image 131
Sergey Kalinichenko Avatar answered Jan 02 '23 11:01

Sergey Kalinichenko


This will not short-circuit the evaluation of the functions for their values, and will return true if any of the functions return false.

bool[] results = new[] {
    IsValidType1(),
    IsValidType2(),
    IsValidType3(),
    IsValidType4() 
};
return results.Any(b => !b);

Note that it reads like your requirement: return true if any of the results are false.

I need to evaluate each of the IsValidType functions. So I can't short-circuit it out.

This must mean that the functions have side effects that you need to observe. Just make sure that you document your code so that no one sees this and doesn't realize that changing it to short-circuit the function evaluation could introduce bugs by removing the side effects.

As far as I can tell, the above will fail because true | true is false.

I am not sure what makes you think that. true | true, that is true or true is true. You might be thinking of xor, but that would be true ^ true.

like image 41
jason Avatar answered Jan 02 '23 11:01

jason