Consider the following code:
bool funcExecuted = false;
bool result = false;
Func<bool> returnFalse = () =>
{
funcExecuted = true;
return false;
};
result &= returnFalse();
string msg = funcExecuted?"Executed":"Not Executed";
Console.WriteLine(msg);
Expected result:
- I expected to get the message of
Not Executed
Actual result:
- I got the
Executed
message.
Conclusions:
result &= returnFalse();
is compiled to result = result & returnFalse();
rather than result = result && returnFalse();
(I expected the latter).
My question is, why is that?
I would expect it to be the other way around. We all use the &&
operator much more commonly than the &
operator and I would expect it to be the "default behaviour".
Update:
Most answers seems to answer the wrong question.
I am aware of the fact that the difference between &&
and &
is that &&
is short-circuiting, whereas &
always evaluates both operands.
The question was why does a &= b
translates into a = a & b;
rather than a = a && b;