Home
Search
VB.NET Select Case ExamplesUse the Select Case statement with integers, Chars and Strings. See a nested Select Case.
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).
Matching. 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.
Else Case Else is the default case. When no other values match, this case is reached.
VB.NET program that uses Select Case
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.
StartsWith, EndsWith
Chars The example uses chars within a String as the Select Case expression. This is a common construct.
Char
VB.NET program that uses nested Select Case
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).
To start Let's evaluate a program that reads an input from the Console. Then it uses the Select Case statement on that value.
Values It matches against four possible values: "dot", "net", and "perls", and also all other values (Else).
VB.NET program that uses Select Case on String
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.
Integer
Note 2 An advanced compiler could analyze this program before execution so that no branches are evaluated at runtime.
VB.NET program that uses variable Cases
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.
VB.NET program that uses stacked 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.
IsValidNumber This is a Boolean Function that returns True if the argument integer is valid, and False for all other numbers.
Case 100, 200 IsValidNumber considers the numbers 100 and 200 to be valid, but all other integers are not valid (according to its logic).
VB.NET program that returns from Select Case
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
ISVALIDNUMBER: True ISVALIDNUMBER: True ISVALIDNUMBER: False
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.
VB.NET program that has duplicate case statements
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
FIRST CASE REACHED
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.
VB.NET program that times If Then, Select Case
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
A discussion. On values, Select Case is implemented with the switch opcode in the intermediate language. This is the same implementation as the switch keyword from the C# language.
Note With this opcode, Select Case is faster (on certain programs and data) than an If-statement.
Performance, overview. Performance of Select Case is highly dependent on both the cases, and the data, in your program. We must use our reasoning ability to figure out the best solution.
And If we have 1,000 cases, but one is most common, testing for the common one with an If-statement is fastest.
Performance, strings. On Strings, does Select Case ever compile into anything other than a series of comparisons? In my tests of various string counts, no Dictionary was used.
Thus VB.NET seems to lack the String Dictionary optimization for C# string switch constructs.
And If you have to match many string literals, building a Dictionary (and using TryGetValue might be faster.
Dictionary
Frequencies. If the frequency of cases is equally distributed, and the values are close together, a Select Case is better. The performance difference in most situations is small.
Often It is the best approach to use whatever syntax form (if or switch) is clearest.
Credit Thanks to Leen Boers for helping correct an error in one of the Select Case examples.
A 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.
Home
© 2007-2021 sam allen. see site info on the changelog