Short-circuit evaluation in VB.NET

Short-circuit evaluation in VB.NET

When evaluating an and statement, there is no point testing the right hand side if the left is false.

If (False And SomeOtherCondition) Then        ' ...End If

In this example, there is no point evaluating SomeOtherCondition, because its value has no effect on the overall result of the and statement (false).

If (True Or SomeOtherCondition) Then        ' ...End If

Similiarly, in this example, there is no point evaluating SomeOtherCondition because it will have no effect on the overall result of the or statement. Breaking out of such a statement early is known as short-circuit evaluation, and is performed automatically in many programming languages.

Unfortunately, the And and Or operators VB and VB.NET perform no such optimization, and always evaluate both conditions, regardless of their values.

To alleviate this problem, VB.NET introduces a couple of handy new operators, AndAlso and OrElse:

If (True OrElse SomeOtherCondition) Then        ' SomeOtherCondition will never be evaluatedEnd IfIf (False AndAlso SomeOtherCondition) Then        ' SomeOtherCondition will never be evaluatedEnd If

These two simple additions provide VB.NET programmers with a convenience that has been taken for granted with other languages for years, and allows them to reduce the number of VB/VB.NET’s syntactically bulky flow control statements.