Pergunta

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;
}
Foi útil?

Solução

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;
}

Outras dicas

Replace || with &&

if (index != -1 && pieces[index].Type != PieceType.Rook)

Otherwise the second codition is evaluated if the first is false what you don't want. You want both conditions being true and especially the first one.

That's because you use OR operator. First condition is false, so second starts evaluating.

You should have index != 1 && ....

Also, is index < -1 or >= pieces.Length?

|| will stop evaluating when it finds that something is true. Since index != -1 is false it will evaluate both sides of the expression. If you && it would stop once it finds a false. I would recommend reading up on lazy evulation.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top