Problem with the && operator

Given the following code

    public bool GetFalse()
    {
        return false;
    }
    public bool GetTrue()
    {
        return true;
    }

How to make this expression GetFalse() && GetTrue()execute the second method?

+3
source share
5 answers

You cannot, because the logical closures of the operator I. In general, it is recommended to avoid side effects from such expressions, although there are quite acceptable applications (i.e if( someObj != null && someObj.Value == whatever ).. You can use the bitwise and operator ( &), which is not short-circuited, but again I would not do that.

You must first break these two method calls into variables, and then check if you need to do them.

bool first = SomeMethodCall();
bool second = SomeMethodThatMustExecute();

if( first && second )
{
    // ...
}
+5
source

Try:

GetFalse() & GetTrue()
+6
source

( - , ):

GetFalse() & GetTrue();
+4

This is an optimization problem. Since the first method called in the expression is false, the whole expression cannot be true, so the second method in the expression is not called. If you need to call it for a side effect (bad practice relying on a side effect, but YMMV), you should use something like this:

x = GetFalse(); 
y = GetTrue(); 
if (x && y) ...
0
source

Assuming your actual functions perform some specific tasks and return a value indicating (for example) success or failure, I would prefer it to be written as

bool fooResult = DoFoo();
bool barResult = DoFar();

And then you can use fooResult && barResultin your code.

0
source

All Articles