Select Case statement in

Select case statement is the good alternate of the if-else statement. If we want to handle multiple values of a variable and don’t not want to use many if-else statement then we should use Select case. Simply Select case test an expression or condition, and execute the code of matching case.


Select Case condition-expression
[Case expressionlist-n
[statements-n]] …
[Case Else
End Select


In the following example we want to show messagebox according to matching condition

 Private Sub DisplayDay(ByVal _day As String)
        Select Case _day
            Case "Monday"
                MessageBox.Show("Today is Monday")
            Case "Tuesday"
                MessageBox.Show("Today is Tuesday")
            Case "Wednesday"
                MessageBox.Show("Today is Wednesday")
            Case "Thurseday"
                MessageBox.Show("Today is Thurseday")
            Case "Friday"
                MessageBox.Show("Today is Friday")
        End Select
 End Sub

When we call DisplayDay(“Monday”) method, select case statement matches value of _day that is “Monday” from all cases and execute corresponding code.

You can also use multiple expressions or ranges in each Case clause. For example If you need check condition-expression in range, You can use ‘To’ keyword to specify the boundaries of a range of match values. The value of expression1 must be less than or equal to the value of expression2.

      Dim number As Integer = 6
        Select Case number
            Case 1 To 3
                MessageBox.Show("value of number is between 0 to 4")
            Case 4, 5, 6, 7
                MessageBox.Show("value of number is between 3 to 8")
            Case 8 To 15
                MessageBox.Show("value of number is between 7 to 16")
            Case Else
                MessageBox.Show("value of number is Not between 0 and 16")
        End Select

Above, you can see the ‘Case Else’ statement which is used to introduce the else statement to run if no match is found. So if the value of ‘Number’ variable is 17 greater than 16, ‘Case Else’ statement will execute.

You can use use multiple expressions or ranges in each Case clause. For example:

      Dim RollNumber As Integer = 11
        Select Case RollNumber
            Case 1 To 3, 6 To 9, 23, 26, Is = 11
                MessageBox.Show("You are in Group A")
            Case 4, 5, 12
                MessageBox.Show("You are in Group B")
            Case Else
                MessageBox.Show("You are in Group C")
        End Select

The first Case expression is also valid, Is keyword used is not the same as the Is Operator, which is used for reference comparison.