Search code examples
c#lazy-evaluationboolean-expression

Lazy "and" expression evaluation


I've been using the following code block to ask user for input and checking its validity in a console application.

do
{
    Console.Write("Enter X value:");    // prompt
} while (!(int.TryParse(Console.ReadLine(),out temp) && (temp<=10) && (temp>=0))); // repeat if input couldn't be parsed as an integer or out of range

Is it a documented feature that the "&&" (and) expression evaluating is lazy? ie: if first operand is false then it wouldn't parse the second operand? Can I rely on it in production builds? Can I expect that it would behave the same in other compilers?
This is something I picked up in PPCG.SE

Additionally, can the block be made simpler to read or simplified into a oneliner?


Solution

  • Is it a documented feature that the "&&" (and) expression evaluating is lazy?

    Yes as mentioned on the C# reference page:

    The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary. In other words, it's a short-circuiting operator.

    Can I rely on it in production builds? Can I expect that it would behave the same in other compilers?

    Yes, it should always behave the same.

    Additionally, can the block be made simpler to read or simplified into a oneliner?

    Apart from removing some of the redundant parameters, you cannot simplify this with only one line.

    You can, however, make it a bit more readable by hiding the logic of (temp<=10) && (temp>=0) into some method e.g.:

    public static bool IsValidRange(int temp) =>  temp >= 0 && temp <= 10;
    

    then your while condition becomes:

    while (!(int.TryParse(Console.ReadLine(), out temp) && IsValidRange(temp)));
    

    now the name of the method reads as the problem statement IsValidRange.