Wednesday, 14 November 2012

|,|| and &,&& in C#

The && and || operators in C# work very similarly to their And and Or counterparts (& and | in C#).
The difference is that with these operators the second expression is never evaluated
when the first one already determines the outcome of the entire expression
eg: if (userName == “Administrator” && GetNumberOfRecordsFromDatabase() > 0)

Now, GetNumberOfRecordsFromDatabase() will only be executed when the current user is
Administrator. The code will be ignored for all other users, resulting in increased performance for them.

&& in C# is equivalent to AndAlso in C#
|| in C# is equivalent to OrElse in C#

&& and || are not advisable if each and every expression is to be evaluated.

&&' and '||' are what's called "short-circuiting" logical operators.

In the case of &&, if the first operand is false, then it doesn't bother evaluating the second operand, because the whole expression is certain to be false.

In the case of ||, if the first operand is true, then it doesn't bother evaluating the second operand, because the whole expression is certain to be true.

'&' and '|' can also be used as logical operators though it's more common for them to be used as bitwise operators. When they're used as logical operators, both operands are always evaluated.

No comments:

Post a Comment