Search code examples
c#.netif-statementjit

Why IF statement iterate over all AND conditions even if the first is false


In c# i've an IF condition like this

if(x != null && x.myprop != "value")
{
//
}

when x is null why the compiler continues after '&&' operator even if the condition is guarantee to be not satsfied.

i've null exceptions if i do x.myprop when x is null, i know that '?' fix the problem but i can't understand why it continues. Sorry for my bad english.


Solution

  • The && operator in C# short circuits so you cannot possibly be seeing this behaviour.

    The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

    However, are you sure you have not mistakenly used the & operator (which does not short circuit)?

    The binary & operator evaluates both operators regardless of the first one's value, in contrast to the conditional AND operator &&.