The If. . .Then statement tests an expression, which is known as a condition. If the condition is True, the program executes the statement(s) that follow. The If. . .Then statement can have a single-line or a multiple-line syntax. To execute one statement conditionally, use the single-line syntax as follows:
If condition Then statementCode language: VB.NET (vbnet)
Conditions are logical expressions that evaluate to a True/False value and they usually contain comparison operators— equals (=), different (<>), less than (<), greater than (>), less than or equal to (<=), and so on — and logical operators: And, Or, Xor, and Not. Here are a few examples of valid conditions:
If (age1 < age2) And (age1 > 12) Then ... If score1 = score2 Then ...Code language: VB.NET (vbnet)
The parentheses are not really needed in the first sample expression, but they make the code a little easier to read. Sometimes parentheses are mandatory, to specify the order in which the expression’s parts will be evaluated, just like math formulae may require parentheses to indicate the precedence of calculations. You can also execute multiple statements by separating them with colons:
If condition Then statement: statement: statementCode language: VB.NET (vbnet)
Here’s an example of a single-line If statement:
expDate = expDate + 1 If expdate.Month > 12 Then expYear = expYear + 1: expMonth = 1Code language: VB.NET (vbnet)
You can break this statement into multiple lines by using the multiline syntax of the If statement, which delimits the statements to be executed conditionally with the End If statement, as shown here:
If expDate.Month > 12 Then expYear = expYear + 1 expMonth = 1 End IfCode language: VB.NET (vbnet)
The Month property of the Date type returns the month of the date to which it’s applied as a numeric value. Most VB developers prefer the multiple-line syntax of the If statement, even if it contains a single statement. The block of statements between the Then and End If keywords form the body of the conditional statement, and you can have as many statements in the body as needed.
Many control properties are Boolean values, which evaluate to a True/False value. Let’s say that your interface contains a CheckBox control and you want to set its caption to On or Off depending on whether it’s selected at the time. Here’s an If statement that changes the caption of the CheckBox:
If CheckBox1.Checked Then CheckBox1.Text = "ON" Else CheckBox1.Text = "OFF" End IfCode language: VB.NET (vbnet)
This statement changes the caption of the CheckBox all right, but when should it be executed? Insert the statement in the CheckBox control’s CheckedChanged event handler, which is fired every time the control’s check mark is turned on or off, whether because of a user action on the interface or from within your code.
The expressions can get quite complicated. The following expression evaluates to True if the date1 variable represents a date earlier than the year 2008 and either one of the score1 and score2 variables exceeds 90:
If (date1 < ‘ statements End IfCode language: VB.NET (vbnet)
The parentheses around the last part of the comparison are mandatory, because we want the compiler to perform the following comparison first:
score1 < 90 Or score2 < 90Code language: VB.NET (vbnet)
If either variable exceeds 90, the preceding expression evaluates to True and the initial condition is reduced to the following:
If (date1 <Code language: VB.NET (vbnet)
The compiler will evaluate the first part of the expression (it will compare two dates) and finally it will combine two Boolean values with the And operator: if both values are True, the entire condition is True; otherwise, it’s False. If you didn’t use parentheses, the compiler would evaluate the three parts of the expression:
expression1: date1 < 90 expression3: score2 < 90expression2: score1 < Code language: VB.NET (vbnet)
Then it would combine expression1 with expression2 using the And operator, and finally it would combine the result with expression3 using the OR operator. If score2 were less than 90, the entire expression would evaluate to True, regardless of the value of the date1 variable.
Short-Circuiting Expression Evaluation (If…Then)
A common pitfall of evaluating expressions with VB is to attempt to compare a Nothing value to something. An object variable that hasn’t been set to a value can’t be used in calculations or comparisons. Consider the following statements:
Dim B As SolidBrush B = New SolidBrush(Color.Cyan) If B.Color = Color.White Then MsgBox("Please select another brush color") End IfCode language: VB.NET (vbnet)
These statements create a SolidBrush object variable, the B variable, and then examine the brush color and prohibit the user from drawing with a white brush. The second statement initializes the brush to the cyan color. (Every shape drawn with this brush will appear in cyan.) If you attempt to use the B variable without initializing it, a runtime exception will be thrown: the infamous NullReferenceException. In our example, the exception will be thrown when the program gets to the If statement, because the B variable has no value (it’s Nothing), and the code attempts to compare it to something. Nothing values can’t be compared to anything. Comment out the secondstatement by inserting a single quote in front of it and then execute the code to see what will happen. Then restore the statement by removing the comment mark.
Let’s fix it by making sure that B is not Nothing:
If B IsNot Nothing And B.Color = Color.White Then MsgBox("Please select another brush color") End IfCode language: VB.NET (vbnet)
The If statement should compare the Color property of the B object, only if the B object is not Nothing. But this isn’t the case. The AND operator evaluates all terms in the expression and then combines their results (True or False values) to determine the value of the expression. If they’re all True, the result is also True. However, it won’t skip the evaluation of some terms as soon as it hits a False value. To avoid unnecessary comparisons, use the AndAlso operator. The AndAlso operator does what the And operator should have done in the first place: It stops evaluating the remaining terms or the expression because they won’t affect the result. If one of its operands is False, the entire expression will evaluate to False. In other words, if B is Nothing, there’s no reason to compare its color; the entire expression will evaluate to False, regardless of the brush’s color. Here’s how we use the AndAlso operator:
If B IsNot Nothing AndAlso B.Color = Color.White Then MsgBox("Please select another brush color") End IfCode language: VB.NET (vbnet)
The AndAlso operator is said to short-circuit the evaluation of the entire expression as soon as it runs into a False value. As soon as one of the parts in an AndAlso operation turns out to be False, the entire expression is False and there’s no need to evaluate the remaining terms.
There’s an equivalent operator for short-circuiting OR expressions: the OrElse operator. The OrElse operator can speed the evaluation of logical expressions a little, but it’s not as important as the AndAlso operator. Another good reason for short-circuiting expression evaluation is tohelp performance. If the second term of an And expression takes longer to execute (it has to access a remote database, for example), you can use the AndAlso operator to make sure that it’s not executed when not needed.