VB.NET Select Case

.NET Array Class File String Sub Cast Console DataTable DateTime Dictionary Enum Exception For If IndexOf Interface Lambda LINQ List Nothing Parse Process Property Regex Replace Select Sort Split StringBuilder Substring


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.


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

VB.NET program that uses Select Case

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


You typed two



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.


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

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


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


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


Word 1
Word 3
Something else

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.




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.


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



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.

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

	' 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

	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

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


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.


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.