Controlling Code Flow
From Xojo Documentation
The methods you write execute one line at a time from top to bottom, left to right. There will be times when you want your app to execute some of its code based on certain conditions (using comparisons). When your app's logic needs to make decisions it’s called branching. This allows you to control what code gets executed and when. There are two branching statements: If...Then...End If and Select Case.
Contents
If...Then...EndIf
The If...Then...End If statement is used when your code needs to test a Boolean (True or False) expression and then execute code based on its result. If the expression you are testing is True, then the lines of code you place between the If...Then line and the End If line are executed, otherwise they are skipped.
To run your code when the Integer value month is equal to 1:
The part “month = 1” is a boolean expression; it’s either True or False. The variable month is either 1 or it is not 1. Suppose you have a Button that performs an additional task if a particular CheckBox is checked. The value property of a CheckBox is Boolean so you can test it in an If statement like this:
Remember that you can declare local variables using the Var statement inside an If statement. However, such variables go out of scope after the End If statement. For example:
Var a As String
a = "Oops! An error occurred."
End If
Label1.Value = a // out of scope!
If you need the variable after the End If statement, you should declare it local to the entire method, not within the If...End If statement.
If...Then...Else...End If
An If...Then...End If statement can be expanded by including an additional Else clause. In some cases, you need to run some code if a boolean expression is True, but a different set of code if the boolean expression is False. In these situations, you add the Else clause for the code that will run when the boolean expression evaluates to False.
This code sets the text based on a month variable:
Var result As String
If month = 1 Then
result = "It is January"
Else // everything else
result = "Not January"
End If
// result = "Not January"
If...Then...ElseIf...End If
The next step in enhancing your If...Then...End If statement is to have multiple tests when the initial boolean expression is False. For each additional test, you use the ElseIf statement.
If month = 1 Then
result = "It is January."
ElseIf month < 4 Then
result = "It is still Winter."
Else
result = "It is not Winter."
End If
You could, of course, use an additional If...Then...End If statement inside the Else portion of the first If statement to perform another test. However, this adds another End If and needlessly complicates your code. Instead, you can use as many ElseIf statements as you need, followed by an optional final Else statement:
If month = 1 Then
result = "It’s January."
ElseIf month < 4 Then
result = "It’s still Winter."
ElseIf month < 6 Then
result = "It must be Spring."
Else
result = "Summer or Fall".
End If
If the initial condition is False, your code continues to test the ElseIf conditions until it finds one that is True. It then executes the code associated with that ElseIf statement and continues executing the lines of code that follow the End If statement.
If...Then...Else
Dialing it down a bit, a simple If statement can written on one line, provided the code that follows the Then and the (optional) Else statements can all be written on one line. When you use this syntax, you omit the End If statement. Some examples:
If error = 123 Then s = "An error occurred."
If error = 123 Then s = "An error occurred." Else s = "Success"
If error = 103 Then Break
If Operator
For situations where you need to simply return a result based on a boolean expression, you can use the If operator.
The condition is evaluated and if it is True, the resultIfTrue is returned, otherwise resultIfFalse is returned.
For example, this code outputs “Big”:
Because this returns a result, the types of resultIfTrue and resultIfFalse must match (or be able to be converted between each other) and must match the destination type.
Select...Case
When you need to test a property or variable for one of many possible values and then take action based on that value, use a Select Case statement.
Consider the following example that uses If...ElseIf..End If to test a variable (dayNumber) and display the day of the week:
If dayNumber = 2 Then
dayName = "Monday"
ElseIf dayNumber = 3 Then
dayName = "Tuesday"
ElseIf dayNumber = 4 Then
dayName = "Wednesday"
ElseIf dayNumber = 5 Then
dayName = "Thursday"
ElseIf dayNumber = 6 Then
dayName = "Friday"
Else
dayName = "the weekend."
End If
Var result As String = "It is " + dayName
No two of these conditions can be True at the same time. While this method of writing the code works, it’s not that easy to read. This next example uses a Select...Case statement to achieve the same result. It is far easier to read:
Select Case dayNumber
Case 2
dayName = "Monday"
Case 3
dayName = "Tuesday"
Case 4
dayName = "Wednesday"
Case 5
dayName = "Thursday"
Case 6
dayName = "Friday"
Else
MessageBox("the weekend.")
End Select
Var result As String = "It is " + dayName
The Select...Case statement compares the variable or property passed in the first line to each value on the Case statements. Once a match is found, the code between that case and the next is executed.
You can use any variable type in the Select...Case. This example compare text values:
Var dayNumber As Integer
Select Case dayName
Case "Monday"
dayNumber = 2
Case "Tuesday"
dayNumber = 3
End Select
Select...Case statements can contain an Else statement to handle all other values not explicitly handled by a Case.
You can create local variables using the Var statement inside a Case statement. However, such variables go out of scope at the conclusion of the Case statement. For example:
Case 2
Var day As Text
day = "Tuesday"
Else
Var day As Text // new scope
day = "It is NOT Tuesday!")
End Select
// day is now out of scope
To be available after the End Select statement is reached, the variable “day” should be declared prior to the Select...Case statement.
The Select…Case statement works with variables of any data type, including Strings, Integers, Singles, Doubles, Booleans, and Colors. For example, you can compare colors, as in the following example:
c = &cFF0000 // pure red
Select Case c
Case &c00FF00 // green
MessageBox("Green")
Case &cFF0000 // red
MessageBox("Red")
Case &c0000FF // blue
MessageBox("Blue")
End Select
A Case statement can accept more than one value, with different values separated by commas. For example, the following is valid:
c = &cFF0000 // red
Select Case c
Case &c00FF00, &cFF0000 // green, red
MessageBox("Green or Red")
Case &cFF0000 // red
MessageBox(“Red”)
Case &c0000FF // blue
MessageBox("Blue")
End Select
In the preceding example, the first Case statement is True, so its code executes. Although the color passed to Select…Case is Red, the code for the second case does not execute because it is not the first matching case.
The Select Case statement accepts an Else clause. The code in the Else clause executes only if none of the preceding cases match. The Else clause can be written as either "Else" or "Case Else". In the following example, the Case Else clause executes because the color FFFF00 does not match any of the Case statements:
c = &cFF0000 // pure red
Select Case c
Case &c00FF00 // green
MessageBox("Green")
Case &cFF0000 // red
MessageBox("Red")
Case &c0000FF // blue
MessageBox("Blue")
Case Else
MessageBox("None of the above")
End Select
The Case statement can also accept a range of consecutive values using the “To” keyword. For example:
Select Case i
Case 1 To 25
MessageBox("25 or less")
Case 26 To 50
MessageBox("26 to 50")
Case 51 To 100
MessageBox("51 to 100")
End Select
In this example, the third case, “51 to 100”, is true.
You can combine ranges with nonconsecutive values, by separating them with commas, such as:
You can write inequalities with the “Is” keyword and an inequality operator. The syntax is:
For example:
Select Case i
Case Is <= 10
// this case selected
Case Is > 10
// this case not selected
End Select
You can combine inequalities with values, as in:
Select Case i
Case 0, Is <= 10, 100
// case not selected
Case Is > 10, Is < 99
// case selected
End Select
You can even use functions that return a value of the specified data type in a Case statement. Here is a simple example:
Var a As Integer = 2
Select Case i
Case CalcSquare(a)
// case 1
Case a
// case 2
Else
// no match
End Select
The function in the first Case statement is:
In this example, the function squares the value passed to it, so the first Case statement matches.
In the case of a simple function like this, you can write the expression in the Case statement itself. That is, the following is an equivalent matching Case statement:
The Select Case statement can also compare variables that are Objects. The following example uses a Select…Case statement to determine which button the user pressed in a MessageDialog box. The Select Case statement compares objects of type MessageDialogButton to determine which of three possible dialog buttons was pressed.
Var b As MessageDialogButton
d.Icon = MessageDialog.GraphicCaution
d.ActionButton.Caption = "Save"
d.CancelButton.Visible = True
d.AlternateActionButton.Visible = True
d.AlternateActionButton.Caption = "Don’t Save"
d.Message = "Save changes before closing?"
d.Explanation = "If you don't save your changes, you will lose your work."
b = d.ShowModal
Select Case b
Case d.ActionButton
// user pressed Save
Case d.AlternateActionButton
// user pressed Don’t Save
Case d.CancelButton
// user pressed Cancel
End Select
You can also use the IsA operator to determine whether an object is of a particular class. The syntax is:
Here is a simple example. The code in a PushButton.Pressed event handler in a Window:
Case IsA PushButton
MessageBox("I’m a PushButton.")
Case IsA TextField
MessageBox("Nope!")
End Select
The term “Me” refers to the PushButton, so the first Case statement returns true.
Nesting
All of these commands can be nested within each other in order to achieve the desired effect. For example, you can nest an If...Then within a Select...Case:
Case 42
If value2 > 3 Then
MessageBox("Cancel")
End If
End Select