Domanda

Sorry I couldn't think of a better way to formulate my question so it could be a duplicate. I appologize in advance. Normally I would test this myself but I am currently on a workstation where I can't program.

Say we have the following code

public void testFunctions()
{
    if(someFunction1() && someFunction2())
    {
        Console.WriteLine("I will never get here.");
    }
}

private bool someFunction1()
{
    Console.Write("Obviously I got here");
    return false;
}

private bool someFunction2()
{
    Console.WriteLine(", but will I ever get here?");
    return false;
}    

What is the output going to be when I call testFunctions?

Obviously I got here

Or:

Obviously I got here, but will I ever get here?
È stato utile?

Soluzione

I think you're basically asking whether the && short-circuits. It does - if the firstoperand evaluates to false, the second operand isn't evaluated. This is guaranteed by the language specification. From section 7.12 of the C# 5 specification:

The && and || operators are conditional versions of the & and | operators:

  • The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.
  • The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is not true.

(I included the section about || for completeness.)

Altri suggerimenti

The first one will be shown ("Obviously I got here"). As your first method returns false, the second part in the if-statement will not be evaluated. If it was an or expression, the second part would be evaluated and your second output would be shown to the screen.

It's going to be

"Obviously I got here"

Why?

It's pretty simple: The operator '&&' requires both results to be true, in order to return true. And there is no need to check the second condition, if the first one didn't pass already.

However, the operator '&' does pretty much the same, except that it calls both functions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top