0

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?
Jordy
  • 1,816
  • 16
  • 29
  • 1
    In C# you will get "Obviously I got here" and never reach the 2nd condition. This is why if you need to check for a null value you do that first. However, this is not the case in all languages. Javascript, for example, will run both conditions. – Kevin DeVoe Jun 26 '13 at 13:41
  • Javascript will run both conditions? I highly doubt that. Maybe its even dependent on the js engine, but at least in chrome (v8 engine) it does `not` run both functions in an `&&` expression if the first evaluates to false. – Dennis Jun 27 '13 at 05:58
  • Also, as far as i know, in javascript it's exactly the same as in C# - you can also use the `&` operator to always run both sides of the expression. – Dennis Jun 27 '13 at 06:00

3 Answers3

2

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

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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.

Abbas
  • 14,186
  • 6
  • 41
  • 72
1

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.

Jan Berktold
  • 976
  • 1
  • 11
  • 33