Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Assignment operator &=

if I have the following bool:

bool success = true;

Will the following three lines of code store the same results in success:

1 - success &= SomeFunctionReturningABool();

2 - success = success & SomeFunctionReturningABool();

3 - success = success && SomeFunctionReturningABool();

I found an article stating that 1 is a shortcut for 2 - but is 2 the same as 3 or is my application going to explode on execution of this line...

like image 460
Rob Avatar asked Apr 04 '11 10:04

Rob


2 Answers

For boolean type, single & evaluates all operands, while double && only evaluates while necessary (i.e. if the first operand is false, it won't bother to evaluate the second one), also known as "short-circuit" evaluation.

Source: http://msdn.microsoft.com/en-us/library/2a723cdk(v=vs.80).aspx

As for the &= assignment operator, it works same as single &.

like image 94
Fyodor Soikin Avatar answered Nov 16 '22 00:11

Fyodor Soikin


1 and 2 are the same in the same way that the following are the same:

int value += 1;
int value = value + 1;

3 is not the same, as if success is false, SomeFunctionReturningABool() won't get called - which is not what you want.

like image 2
ChrisF Avatar answered Nov 16 '22 01:11

ChrisF