Search code examples
c#short-circuiting

Short circuiting not working


It was my understanding that C# conditional operators perform short circuiting. However, my program throws an exception while running this code. Index is equal to -1, so the second condition should never execute, but I get an index out of bounds exception.

if (index != -1 || pieces[index].Type != PieceType.Rook)
{
    allowed = false;
}

Solution

  • You have used || so when the first condition fails (index IS -1) the runtime needs to check the second condition before excluding the code from execution and that will trigger the exception,

    Instead, you use && (AND) if you want to enter the if only when the two conditions are true.
    In this way, as before, the runtime checks the first condition and now getting the false result is enough to decide that there is no need to check the second condition..

    if (index != -1 && pieces[index].Type != PieceType.Rook)
    {
        allowed = false;
    }