Home > Code, Tips, g33k > Short-Circuiting in C# with OrElse Operator

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?

result
Required. Any Boolean expression.
expression1
Required. Any Boolean expression.
expression2
Required. Any Boolean expression.

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

VN:F [1.9.1_1087]

Rating: 0.0/5 (0 votes cast)
VN:F [1.9.1_1087]
Rating: 0 (from 0 votes)
Categories: Code, Tips, g33k Tags:
  1. No comments yet.
  1. No trackbacks yet.