Share via


How to: Test for Several Values of an Expression

When you are comparing the same expression to several different values, you can use the Select...Case Statement (Visual Basic) construction as an alternative to the If...Then...Else Statement (Visual Basic) construction. Whereas the If and ElseIf (Visual Basic) statements can evaluate a different expression in each statement, the Select statement evaluates a single expression only once and uses it for every comparison.

To evaluate an expression once and test several values

  • Use the Select...Case construction to specify the expression and the values to test. Each Case statement can contain one or more values, a range of values, or a combination of values and comparison operators. You can use a Case Else statement to handle all values not tested by the previous Case statements. The following example illustrates these possibilities.

    Function bonus(ByVal performance As Integer, ByVal salary As Decimal) _
        As Decimal
        Select performance
            Case 1
                Return salary * 0.1
            Case 2, 3
                Return salary * 0.09
            Case 5 To 7
                Return salary * 0.07
            Case 4, 8 To 10
                Return salary * 0.05
            Case Is < 15
                Return 100
            Case Else
                Return 0
       End Select
    End Function
    

    Visual Basic compares the value of the expression to the values in the Case statements in the order they appear in the Select...Case construction. If it finds a match or a Case Else statement, it runs the corresponding statement block. In any case, it then branches to the statement following the End Select statement.

    You can have any number of Case statements, and you can include or omit one Case Else statement regardless of whether you have any Case statements.

A code example for the Select...Case construction is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

See Also

Tasks

How to: Transfer Control Out of a Control Structure

How to: Run Statements Depending on One or More Conditions

How to: Retain Control When an Error Occurs

Concepts

Decision Structures

Loop Structures

Other Control Structures

Nested Control Structures

Other Resources

Control Flow in Visual Basic