Evaluate Conditions Separately with Short-Circuit Logic

In previous versions of VB, there were two logical operators: And and Or. Visual Basic 2005 introduces two new operators that supplement these: AndAlso and OrElse. These operators work in the same way as And and Or, except they have support for short-circuiting, which allows you to evaluate just one part of a long conditional statement.

Note

With short-circuiting, you can combine multiple conditions to write more compact code.

How do I do that?

A common programming scenario is the need to evaluate several conditions in a row. Often, this involves checking that an object is not null, and then examining one of its properties. In order to handle this scenario, you need to use nested If blocks, as shown here:

If MyObject Is Nothing Then
    If MyObject.Value > 10 Then
        ' (Do something.)
    End If
End If

It would be nice to combine both of these conditions into a single line, as follows:

If MyObject Is Nothing And MyObject.Value > 10 Then
    ' (Do something.)
End If

Unfortunately, this won't work because VB always evaluates both conditions. In other words, even if MyObject is Nothing, VB will evaluate the second condition and attempt to retrieve the MyObject.Value property, which will cause a NullReferenceException.

Visual Basic 2005 solves this problem with the AndAlso and OrElse keywords. When you use these keywords, Visual Basic won't evaluate the second condition if the first condition is false. Here's the corrected code:

If MyObject Is Nothing ...

Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.