-3

If I have

if (false && true) 
    ...

can I be sure that every computer/compiler/whatever will do the shortcut that ignores the second condition? In my implementation, the second condition assumes that the first is true, otherwise it will cause a fatal error. For example:

if (Foobar is BoolContainer && Foobar.BoolVar)
    ...

where BoolContainer is an example class with a boolean property BoolVar.

  • 1
    I recommend to rephrase so that "Yes." is not an answer. I.e. ask for explanations or quotes from standard. – Yunnosch Jun 08 '21 at 02:19
  • 3
    `&&` requires both the conditions to be true in order to execute the code in the `if` block. So yes, if the first condition is not true then it will not check for the second condition and evaluates as false and skip the execution of `if` block. – Chetan Jun 08 '21 at 02:19
  • 1
    @ChetanRanpariya Please answer in answer posts instead of in comments. – Yunnosch Jun 08 '21 at 02:20
  • You might be interested in [this question](https://stackoverflow.com/questions/5537607/usage-of-versus), specifically [this answer](https://stackoverflow.com/a/50108836/3181933) – ProgrammingLlama Jun 08 '21 at 03:13

5 Answers5

3

MSDN states(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators):

The conditional logical AND operator &&, also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true. Otherwise, the result is false. If x evaluates to false, y is not evaluated.

So your assumption is correct. Though you should be careful when you use &:

The & operator computes the logical AND of its operands. The result of x & y is true if both x and y evaluate to true. Otherwise, the result is false.

The & operator evaluates both operands even if the left-hand operand evaluates to false, so that the operation result is false regardless of the value of the right-hand operand.

You might get unwanted evaluation when you use &.

MarkSouls
  • 982
  • 4
  • 13
  • So even if I'm writing code that will be compiled for different operating systems, it's ALWAYS a safe assumption (as long as I'm careful to use `&&` and not `&`)? – Justin Iaconis Jun 08 '21 at 02:38
  • 2
    @JustinIaconis the C# spec requires the && operator to short circuit. Any C# compiler that evaluates the right side when the left side is false has a bug. The C# compiler produces IL, so there should be no way for the just-in-time compiler for a particular platform to undo the short circuiting evaluation. – phoog Jun 08 '21 at 02:54
2

There is an extreme edge case where && won't necessarily do what you expect. You won't experience this in normal code. ;)

In the below code both booleans will output as True, but if you && them the result will (on some versions of .NET, but not all) not be True (because true2 is an "unusual" true).

Again, this is not something you will ever experience in real life.

namespace MyNamespace
{
    using System;
    using System.Runtime.InteropServices;

    namespace Work
    {
        [StructLayout(LayoutKind.Explicit)]
        public struct HackedBoolean
        {
            [FieldOffset(0)] public int value;
            [FieldOffset(0)] public bool boolean;
            public bool GetBool(int seed)
            {
                value = seed;
                return boolean;
            }
        }

        public class MyClassCS
        {
            public static void Main(string[] args)
            {
                var hacked = new HackedBoolean();
                var true1 = hacked.GetBool(1);
                var true2 = hacked.GetBool(2);

                Console.WriteLine(true1);
                Console.WriteLine(true2);
                Console.WriteLine(true1 && true2);
                Console.WriteLine(true1 == true2);

                Console.ReadLine();
            }
        }
    }
}
mjwills
  • 23,389
  • 6
  • 40
  • 63
1

Yes it is safe. If you want both sides to be evaluated you can use & instead of &&. Otherwise it will skip second condition in this case.

Klamsi
  • 846
  • 5
  • 16
1

As per the documentation of Conditional Logical ANN operator && on MSDN condition using && operator evaluates to true only when all the conditions evaluates to true.

If any of the conditions evaluates to false, the entire evaluations results as false.

while evaluating the conditions from left to right, next condition is not evaluated if the previous one evaluates to false.

Chetan
  • 6,711
  • 3
  • 22
  • 32
-1

Yes, it is guaranteed by the language specification:

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

In my experience it is a very common idiom for the second part of a short-circuiting conditional expression like this to rely on this behavior.

You might be wondering about why it says "not false" instead of "true". For a bool type, these two are equivalent. At first I thought it was because bool? had a lifted operator to deal with null, but this is not the case. But you can do something similar with a type that overloads the true, false, &, and | operators, and in fact the spec provides the DBBool example struct which does just that.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34