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.
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
.
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 Module2 RESULT: two
Sometimes a nested Select Case
statement is useful. For example, we can test characters in a String
, one after another, with nested Selects.
StartsWith
or EndsWith
calls. This is only needed on performance-critical code.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 ModuleString starts with c, a
Select Case
may be used on a String
. With this statement we match a variable against a set of values such as String
literals.
Select Case
offers no performance advantage as with Integers (or other values).Console
. Then it uses the Select Case
statement on that value.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 Moduledot Word 1 perls Word 3 test Something else
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.
Select Case
statement.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 ModuleValue equals y
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.
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 Module99: 99 or 100 100: 99 or 100
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.
Boolean
Function that returns True if the argument integer is valid, and False for all other numbers.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 ModuleISVALIDNUMBER: True ISVALIDNUMBER: True ISVALIDNUMBER: False
In VB.NET we can have duplicate case statements. Only the first matching case statement will be reached. No errors or warnings are encountered.
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 ModuleFIRST CASE REACHED
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.
If
-statement, along with ElseIf
to test values.Select Case
statement, along with Cases, to test for possible values.Select Case
statement is faster. The results are the same for the constructs.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 Module1.47 s: If Then, value = 2 0.86 s: Select Case, value = 2
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.