When to use And, Andalso and Or, Orelse?

Asked

Viewed 506 times

2

I don’t know when to use the syntax Or or OrElse and/or And or AndAlso, because I don’t understand what difference it makes in the logic circuit.

Being in C#, And = &, AndAlso = && and Or = |, OrElse = ||.

I need to test the following expression to know if the whole lastToken is zero (0) and also if it is greater than 2:

if(lastToken == 0 & lastToken > 2) { ... }

But I don’t know if I use & or &&.

Which one should I use?

1 answer

2


Good Afternoon.

& and && are the same comparisons, however:

If you have a Expression1 & Expression2, he’ll check both, soon you’ll spend more time.

If you have Expression1 && Expression2, he will check the first and only check the second if the first is true.

If you are studying, use any one, but there will come a time when the speed of your code will influence.

Or and Orelse follows the same logic.

  • Let me get this straight, & checks the two expressions if both are true, the expression itself is true, if one is false, the expression is false?

  • 1

    Yes, and that could be a waste of time. Logically if an expression with AND has at least one False, there is no need to check the other, so there is &&, it checks the first and ends there even if it is false.

  • Did you forget to mention that & is an arithmetic operator while && is a logical operator. The expression 21 & 1 is valid but the expression 21 && 1 is not valid.

  • I particularly don’t like to use the operator & (that will always be called to me bitwise-and) if it is not an operation that I know beforehand that I will do operations on the bits. Like, when I want that 3 & 1 be true and 6 & 1 be false

Browser other questions tagged

You are not signed in. Login or sign up in order to post.