Select Case
Prerequisites: If statements
Select Case compares one value against several cases — clearer than a
long chain of ElseIfs:
Module Program
Function Describe(n As Integer) As String
Select Case n
Case 0
Return "zero"
Case 1, 2, 3
Return "small"
Case 4 To 9
Return "medium"
Case Is < 0
Return "negative"
Case Else
Return "large"
End Select
End Function
Sub Main()
For Each n In {0, 2, 7, -5, 100}
Console.WriteLine($"{n}: {Describe(n)}")
Next
End Sub
End Module
0: zero
2: small
7: medium
-5: negative
100: large
- A case can list values (
1, 2, 3), a range (4 To 9), or a comparison (Is < 0). - Only the first matching case runs — there's no fall-through, so
no
breakis needed. Case Elsehandles everything not matched.
Strings and other types
Module Program
Sub Main()
For Each dayName In {"Saturday", "Monday", "Holiday"}
Select Case dayName
Case "Saturday", "Sunday"
Console.WriteLine($"{dayName}: weekend")
Case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
Console.WriteLine($"{dayName}: weekday")
Case Else
Console.WriteLine($"{dayName}: unknown")
End Select
Next
End Sub
End Module
Saturday: weekend
Monday: weekday
Holiday: unknown
Ranges work on strings too, but alphabetically: Case "A" To "M"
matches any text that sorts between "A" and "M". A range like
"Monday" To "Friday" would match nothing at all, because "Friday"
sorts before "Monday" — so list the day names explicitly, as above.
Select Case True
A common VB idiom tests unrelated conditions in order:
Module Program
Sub Main()
Dim bmi = 23.4
Select Case True
Case bmi < 18.5
Console.WriteLine("underweight")
Case bmi < 25
Console.WriteLine("normal")
Case Else
Console.WriteLine("overweight")
End Select
End Sub
End Module
normal
Practice
Write a function DaysInMonth(month As Integer) As Integer for a
non-leap year using Select Case, and print the result for months 2, 4,
and 12.
Show solution
Module Program
Function DaysInMonth(month As Integer) As Integer
Select Case month
Case 2
Return 28
Case 4, 6, 9, 11
Return 30
Case Else
Return 31
End Select
End Function
Sub Main()
For Each m In {2, 4, 12}
Console.WriteLine($"Month {m}: {DaysInMonth(m)} days")
Next
End Sub
End Module
Month 2: 28 days
Month 4: 30 days
Month 12: 31 days