Sunday, April 21, 2013

How do the C# operators |, ||, & and && differ?

|| and && are "short-circuit" operators for "OR" and "AND" operations respectively.
For instance, consider the below conditional check.
           if(predicate1 || predicate2 || predicate3)
           {
                // Some code.
           }
Here, if predicate1 is true, predicates 2 and 3 will not be checked. If predicate1 is false and predicate2 is true, then predicate3 will not be checked.

Similarly,
           if(predicate1 && predicate2 && predicate3)
           {
                // Some code.
           } 
Here, if predicate1 is false, predicates 2 and 3 will not be checked. If predicate1 is true and predicate2 is false, then predicate3 will not be checked.

| and & mean different based on the type of the operands.
If they are used on non-integer operands, then they act as normal logical operators. However, not short-circuited, i.e., All the conditions/predicates in a conditional statement are checked, irrespective of the result of any of the predicates.
           if(predicate1 || predicate2 || predicate3)
           {

                // Some code.

           }
the above checks all three conditions, even if predicate1 is true.

 If they are used on integer operands, then the act as bitwise operators, for instance,             A = 01010101                B = 10101011          A | B = 11111111A & B = 00000001

 
Please comment if this served your purpose by any chance. Happy coding :)