Short-circuit Conditionals in VB.NET

I found myself searching for this several times.

The two operators for short-circuit evaluation are ‘AndAlso’ and ‘OrElse’.

If (conditionOne) AndAlso (conditionTwo) Then

….

End If

If (conditionOne) is false, (conditionTwo) is not evaluated.

If (conditionOne) OrElse (conditionTwo) Then

….

End If

If (conditionOne) is true, (conditionTwo) is not evaluated.

The improvements in performance/efficiency of a program are probably negligible here. However, there may be situations where short-circuit/lazy evaluation can prevent an error — a situation where the second condition depended on the first. For example, the ‘AndAlso’ operator could be used to check the existence of an object before attempting to reference its property.

Advertisements