10.8.2 Select...Case Statements
A Select Case statement executes statements based on the value of an expression. The expression must be classified as a value and its type must be a primitive type or Object.
When a Select Case statement is executed, the Select expression is evaluated first, and the Case statements are then evaluated in order of textual declaration. The first Case statement that evaluates to True has its block executed. If no Case statement evaluates to True and there is a Case Else statement, that block is executed. Once a block has finished executing, execution passes to the end of the Select statement.
Execution of a Case block is not permitted to "fall through" to the next switch section. This prevents a common class of bugs that occur in other languages when a Case terminating statement is accidentally omitted. The following example illustrates this behavior:
Module Test Sub Main() Dim x As Integer = 10 Select Case x Case 5 Console.WriteLine("x = 5") Case 10 Console.WriteLine("x = 10") Case 20 – 10 Console.WriteLine("x = 20 – 10") Case 30 Console.WriteLine("x = 30") End Select End Sub End Module
The code prints:
x = 10
Case 10 and
Case 20 – 10 select for the same value,
Case 10 is executed because it precedes
Case 20 – 10 textually. When the next Case is reached, execution continues after the Select statement.
A Case clause may take two forms. One form is an optional Is keyword, a comparison operator, and an expression. The expression is converted to the type of the Select expression; if the expression is not implicitly convertible to the type of the Select expression, a compile-time error occurs. If the Select expression is E, the comparison operator is Op, and the Case expression is E1, the case is evaluated as E OP E1. The operator must be valid for the types of the two expressions; otherwise a compile-time error occurs.
The other form is an expression optionally followed by the keyword To and a second expression. Both expressions are converted to the type of the Select expression; if either expression is not implicitly convertible to the type of the Select expression, a compile-time error occurs. If the Select expression is E, the first Case expression is E1, and the second Case expression is E2, the Case is evaluated either as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2). The operators must be valid for the types of the two expressions; otherwise a compile-time error occurs.
SelectStatement ::= Select [ Case ] Expression StatementTerminator [ CaseStatement+ ] [ CaseElseStatement ] End Select StatementTerminator CaseStatement ::= Case CaseClauses StatementTerminator [ Block ] CaseClauses ::= CaseClause | CaseClauses , CaseClause CaseClause ::= [ Is ] ComparisonOperator Expression | Expression [ To Expression ] ComparisonOperator ::= = | < > | < | > | = > | = < CaseElseStatement ::= Case Else StatementTerminator [ Block ]