Select Case Examples
This page was last reviewed on Nov 11, 2023.
Dot Net Perls
Select Case. In branches (selection statements) programs change course. Select Case rapidly matches values. In it, we specify a set of constants (Integers, Chars, Strings).
Select Case evaluates an expression and goes to the matching clause. Cases do not fall through, and no "exit" statement is required. But we can stack cases that share statements.
First example. To create a Select Case statement, type Select and press tab. Then, edit the variable name. We read a line from the Console, call Integer.Parse on it, and then use Select.
Info Case Else is the default case. When no other values match, this case is reached.
Module Module1 Sub Main() ' Read in from console. Dim value As Integer = Integer.Parse(Console.ReadLine()) Dim result As String ' Set result with Select Case. Select Case value Case 1 result = "one" Case 2 result = "two" Case 5 result = "five" Case Else result = "?" End Select ' Write result. Console.WriteLine("RESULT: {0}", result) End Sub End Module
2 RESULT: two
Nested. Sometimes a nested Select Case statement is useful. For example, we can test characters in a String, one after another, with nested Selects.
And We can use this style of logic to optimize StartsWith or EndsWith calls. This is only needed on performance-critical code.
String StartsWith
Detail The example uses chars within a String as the Select Case expression. This is a common construct.
Module Module1 Sub Main() Dim value As String = "cat" ' Handle first letter. Select Case value(0) Case "c" ' Handle second letter. Select Case value(1) Case "a" Console.WriteLine("String starts with c, a") Case "o" ' Not reached: Console.WriteLine("String starts with c, o") End Select End Select End Sub End Module
String starts with c, a
Strings. Select Case may be used on a String. With this statement we match a variable against a set of values such as String literals.
But On Strings, Select Case offers no performance advantage as with Integers (or other values).
Detail Let's evaluate a program that reads an input from the Console. Then it uses the Select Case statement on that value.
Detail It matches against four possible values: "dot", "net", and "perls", and also all other values (Else).
Module Module1 Sub Main() While True Dim value As String = Console.ReadLine() Select Case value Case "dot" Console.WriteLine("Word 1") Case "net" Console.WriteLine("Word 2") Case "perls" Console.WriteLine("Word 3") Case Else Console.WriteLine("Something else") End Select End While End Sub End Module
dot Word 1 perls Word 3 test Something else
Variables. VB.NET allows variable cases. But we may lose optimizations with this syntax. Each case must be evaluated and cannot be stored in a lookup table.
Note The "value" Integer is set to 10. And we match it against the variable y, which also equals 10, in a Select Case statement.
Note 2 An advanced compiler could analyze this program before execution so that no branches are evaluated at runtime.
Module Module1 Sub Main() Dim value As Integer = 10 Dim x As Integer = 5 Dim y As Integer = 10 ' Select with cases that are variables. Select Case value Case x ' Not reached. Console.WriteLine("Value equals x") Case y Console.WriteLine("Value equals y") End Select End Sub End Module
Value equals y
Stacked cases. Multiple cases can be combined by specifying them one after another. In this example, both 99 and 100 will reach the same Console.WriteLine statement.
Important Stacked cases must be specified on the same line. Separate "case" statements mean empty blocks of code, not a group of cases.
Module Module1 Sub Main() Dim value As Integer = Integer.Parse("99") Select Case value Case 99, 100 ' Both 99 and 100 will end up here. Console.WriteLine("99 or 100") Case 101 Console.WriteLine("Not reached") End Select End Sub End Module
99: 99 or 100 100: 99 or 100
Return. It is possible to return from a Function or Subroutine with a Return statement within a Select Case. This can reduce the lines of code required to express some logic.
Detail This is a Boolean Function that returns True if the argument integer is valid, and False for all other numbers.
Detail IsValidNumber considers the numbers 100 and 200 to be valid, but all other integers are not valid (according to its logic).
Module Module1 Function IsValidNumber(ByVal number As Integer) As Boolean ' Return from a Select Case statement in a Function. Select Case number Case 100, 200 Return True End Select ' Other numbers are False. Return False End Function Sub Main() Console.WriteLine("ISVALIDNUMBER: {0}", IsValidNumber(100)) Console.WriteLine("ISVALIDNUMBER: {0}", IsValidNumber(200)) Console.WriteLine("ISVALIDNUMBER: {0}", IsValidNumber(300)) End Sub End Module
Duplicate cases. In VB.NET we can have duplicate case statements. Only the first matching case statement will be reached. No errors or warnings are encountered.
Note Duplicate cases could mean an error in a program. It might be best to order cases from low to high to easily spot this issue.
Module Module1 Sub Main() Dim value As Integer = 1 Select Case value Case 1 Console.WriteLine("FIRST CASE REACHED") Case 1 Console.WriteLine("SECOND CASE") End Select End Sub End Module
Benchmark. With Integers, Select Case often is faster than an If-Statement. Consider this benchmark. It tests an If-ElseIf construct and an equivalent Select Case. The value equals 2.
Version 1 In this version of the code, we use an If-statement, along with ElseIf to test values.
If Then
Version 2 Here we use the Select Case statement, along with Cases, to test for possible values.
Result The Select Case statement is faster. The results are the same for the constructs.
Info Try changing the value to 0, not 2. The If-statement will perform faster, because the first check matches the value each time.
Module Module1 Sub Main() Dim m As Integer = 300000000 Dim value As Integer = 2 ' Version 1: Use If-Statement. Dim total As Integer = 0 Dim s1 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 If value = 0 Then total -= 1 ElseIf value = 1 Then total -= 100 ElseIf value = 2 Then total += 1 End If Next s1.Stop() ' Version 2: Use Select Case. total = 0 Dim s2 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Select Case value Case 0 total -= 1 Case 1 total -= 100 Case 2 total += 1 End Select Next s2.Stop() Console.WriteLine((s1.Elapsed.TotalMilliseconds / 1000).ToString("0.00 s")) Console.WriteLine((s2.Elapsed.TotalMilliseconds / 1000).ToString("0.00 s")) End Sub End Module
1.47 s: If Then, value = 2 0.86 s: Select Case, value = 2
Summary. The Select Case statement optimizes selection from several constant cases. This special syntax form can be used to test a variable against several constant values.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 11, 2023 (simplify).
© 2007-2024 Sam Allen.