문제

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?
도움이 되었습니까?

해결책

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.)

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top