TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

VB.NET Select Case Examples: Strings and Integers

These VB.NET example programs use the Select Case statement with integer, Char and String cases. A nested Select Case is shown.

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

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.

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

Output

2
You typed 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

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

Output

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

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 "deves", 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 "deves"
		    Console.WriteLine("Word 3")
		Case Else
		    Console.WriteLine("Something else")
	    End Select
	End While
    End Sub
End Module

Output

dot
Word 1
deves
Word 3
test
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.

Result: No Dictionary was used by the compiler. 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. 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

Output

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.

VB.NET program that uses stacked cases

Module Module1

    Sub Main()
	Dim value As Integer = Integer.Parse("100")
	Select Case value
	    Case 99
	    Case 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

Output

99 or 100

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

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.

Results 2

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

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.

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.

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.

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

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf