Using & = for boolean values ​​in C #

I have a method in C # called SendEvent

that returns bool

that represents whether it was successful or not. I want to loop through several objects and call SendEvent

on all of them, and at the end get the result variable, which is bool

, that is true

, if all calls SendEvent

are successful and false

if at least one fails.

First I did this:

bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
    result = result && myObjects[i].SendEvent();
}

      

But this will result in SendEvent

not being called on subsequent objects if it fails, since the right side of the statement &&

will fail if the result false

.

So, I flipped it over to:

bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
    result = myObjects[i].SendEvent() && result;
}

      

But I found this somewhat ugly. Can I use the bitwise operator &=

to make the call SendEvent

and set the value of the result, for example:

bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
    result &= myObjects[i].SendEvent();
}

      

How does it work &=

for boolean values? Will it do both sides of the operator? What will be in the result variable?

+3


source to share


2 answers


As you can read here , both &

and are &&

defined for bool

s
as "boolean and", but will be short-circuited: if the first operand the expression on the right is not evaluated. No matter what the result of the expression on the right is, the result of the expression will remain . This is usually a "performance hack", but if the correct expression has side effects, can throw an exception, etc., this is something you should consider. The same happens for an operator if the first operand is . &&

false

&&

false

||

true

So, if you want to evaluate both sides first , you can actually use:

result = result & myObjects[i].SendEvent();

      

or shorter:

result &= myObjects[i].SendEvent();

      



Background

As written in the language specifications :

Operation

x && y  

      

corresponds to operation

x & y  

      

except that if x

- false

, is y

not evaluated because the result of the AND operation is false

whatever the value y

is. This is called the "short circuit" rating.

Please note that there is no &&=

operator
(at least at the time I write this). This looks reasonable, since usually with an operator, ..=

you should expect the operand to be evaluated first and then some variable left operation to be performed. Of course, it's all about style and taste, but I would assume that the hypothetical &&=

doesn't give "enough hints" that the right-hand operand won't be called in all cases.

+8


source


As a LINQ lover, I would do it like:

var result = (myObjects.Count(obj => obj.SendEvent()) == myObjects.Length);

      



If you want to break the loop on the first value false

, it should be:

var result = myObjects.All(obj => obj.SendEvent());

      

+6


source







All Articles