I have a method in C# called SendEvent
that returns a bool
which represents if it was successful or not. I want to loop through a number of objects and call SendEvent
on them all, and in the end, have a result variable that is a bool
, that is true
if all SendEvent
calls succeeded, and false
if at least one failed.
At first I did this:
bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
result = result && myObjects[i].SendEvent();
}
But that will cause that the SendEvent
will not be called on subsequent objects if one fails, as the right hand side of the &&
operator won't be executed if result is false
.
So I turned it around, to:
bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
result = myObjects[i].SendEvent() && result;
}
But I found that somewhat ugly. Can I use the bitwise &=
operator to always execute the SendEvent
call, and set the value of result, like this?
bool result = true;
for (int i = 0; i < myObjects.Length; i++)
{
result &= myObjects[i].SendEvent();
}
How does the &=
work on boolean values? Will it execute both sides of the operator? What will end up in the result variable?