VB.NET Select Case

Array Collections File Keyword String Cast Class Console Data Directive Enum Exception If Interface Lambda LINQ Loop Nothing Number Process Property Regex Select Sort StringBuilder Structure Sub Time Windows

Case

In branches,
in 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.

Example

To create a new Select Case statement, type Select and then press tab. Then, edit the variable name to be appropriate for your program. We read a line from the Console, call Integer.Parse on it, and then Select it from a set of cases.

Else:Case Else is the default case.
When no other values match, this case is reached.

Based on:

.NET 4.5

Program that uses Select Case: VB.NET

Module Module1
    Sub Main()
	Dim value As Integer = Integer.Parse(Console.ReadLine())
	Select Case value
	    Case 1
		Console.WriteLine("You typed one")
	    Case 2
		Console.WriteLine("You typed two")
	    Case 5
		Console.WriteLine("You typed five")
	    Case Else
		Console.WriteLine("You typed something else")
	End Select
    End Sub
End Module

Output

2
You typed two

Nested

Logic

Sometimes a nested Select Case statement is useful.
For example,
we can test characters in a String,
one after another,
with nested Selects. This is an efficient, and fairly clear, way to test String data.

And:We can use this style of logic to optimize StartsWith or EndsWith calls. This is only needed on performance-critical code.

StartsWith

Chars:The example uses chars within a String as the Select Case expression. This is a common construct.

Char
Program that uses nested Select Case: VB.NET

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

Output

String starts with c, a

Strings

String face

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).

Strings

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).

Program that uses Select Case on String: VB.NET

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

Output

dot
Word 1
perls
Word 3
test
Something else
Net

Internals. On Strings, does Select Case ever compile into anything other than a series of comparisons? I changed the above program to have nine String literals. No Dictionary collection was used by the compiler.

So:It seems that VB.NET lacks the String Dictionary optimization for C# String Switch constructs.

Therefore:If you have to match a lot of string literals, building a Dictionary might be faster.

Dictionary

Variables

Method

Variable cases are allowed. But we may lose optimizations with this syntax—each case must be evaluated and cannot be stored in a lookup table. The compiled cannot use the switch opcode.

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.

Program that uses variable Cases: VB.NET

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

Output

Value equals y

Performance

Program

With Integers, Select Case often is faster than an If-Statement. Consider this benchmark.
It first tests,
in a tight loop,
an If-ElseIf construct. It then tests an equivalent Select Case statement. The value equals 2 here.

If Then

Result:The Select Case statement is faster.
The results are the same for the constructs.

Thus:In many programs, Select Case is an optimization. But if we have one case that occurs most often, If may be faster—see the next test.

Program that times If Then, Select Case: VB.NET

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

Results

1.47 s:   If Then,     value = 2
0.86 s:   Select Case, value = 2
Performance

An experiment. I changed the benchmark to set the "value" Integer to 0, not 2. Now the first If-expression evaluates to true every time. Fewer branches are needed, and the If is faster than the Select Case.

Results 2

0.89 s:   If Then,     value = 0
1.14 s:   Select Case, value = 0

Discussion

Cover logo

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. With this opcode, Select Case can be faster than an If-statement.

However:Performance of Select Case is highly dependent on both the cases, and the data, in your program.

And:If we have 1,000 cases, but one is most common, testing for the common one with an If-statement is fastest.

Percentage symbol

If the frequency of all cases is equally distributed, and the cases are close together in numeric value, then a Select Case is better. The performance difference in most situations is small.

Tip:It is often the best approach to just use whatever syntax form is clearest.

Summary

The VB.NET programming language

The Select Case statement in the VB.NET language provides an optimized way of selecting from several constant cases. This special syntax form can be used to test a variable against several constant values.

VB.NET