2.13. 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.
2.13.1. 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 AndAlso MyObject.Value > 10 Then ' (Do something.) End If
2.13.2. What about...
...other language refinements? In this chapter, you've had a tour of the most important VB language innovations. However, it's worth pointing out a few of the less significant ones that I haven't included in this chapter: