Short-Circuiting in C# with OrElse Operator
I’d heard about short-circuiting before but had never seen it actually applied. I guess the main benefit of the OrElse operator is that it can improve performance if the “bypassed” condition is cumbersome. It’s basically an OR statement, but if the first expression evaluates as TRUE, it doesn’t need to evaluate the second expression. Normally, both expressions would be evaulated, but in reality, if the first one is TRUE, the whole condition is TRUE, so why evaluate the second one, right?
| If expression1 is | And expression2 is | Then result is |
|---|---|---|
| True | (not evaluated) | True |
| False | True | True |
| False | False | False |
It’s this simple:
Dim A As Integer = 10
Dim B As Integer = 8
Dim C As Integer = 6
Dim myCheck As Boolean
myCheck = A > B OrElse B > C ' True. Second expression is not evaluated.
myCheck = B > A OrElse B > C ' True. Second expression is evaluated.
myCheck = B > A OrElse C > B ' False.
If MyFunction(5) = True OrElse MyOtherFunction(4) = True Then
' If MyFunction(5) is True, MyOtherFunction(4) is not called.
' Insert code to be executed.
End If
Recent Buzz