Monday, October 1, 2012

Using AndAlso & OrElse

The 'And' operator evaluates both sides, where 'AndAlso' only evaluates the right side if the left side is true.


the And operator will check all conditions in the statement before continuing, whereas the Andalso operator will stop if it knows the condition is false. For example:
if x = 5 And y = 7
Checks if x is equal to 5, and if y is equal to 7, then continues if both are true.
if x = 5 Andalso y = 7
Checks if x is equal to 5. If it's not, it doesn't check if y is 7, because it knows that the condition is false already. (This is called short-circuiting)
Generally people use the short-circuiting method, because it saves on runtime. However, if the second action (in this case y = 7) has a side effect that you want to run whether the first is true or not, i.e.:
if x == 5 And Object.Load()
If you use OR, then both Expression1 and Expression2 will be evaluated. If either is True then the Result is True.
However, if you use ORELSE and Expression1 is found to be True then Expression2 is not evaluated.

No comments: