VB.NET Select Case String

Select method call

You want to use the VB.NET Select Case statement on a String argument. With the Select Case statement, you match a variable against a set of values such as String literals. We look at the Select Case statement in the VB.NET language and look at its implementation.

Example

Note

To start, let's look at a program that reads an input from the Console. Then, it uses the Select Case statement on that value. It matches against four possible values: "dot", "net", and "perls", and also all other values (Else).

This VB example program shows how to use the Select Case statement with string cases.

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

Case values. In the VB.NET language, you can actually use variables in the Case expressions. However, you may lose some optimizations if you do this. In integer Select Case statements, if you use a non-constant integer, you may lose performance because the switch opcode cannot be used.

Select Case Example switch Instruction

Implementation

.NET Framework information

Does the Select Case statement in the VB.NET language ever compile into anything other than a series of string comparisons? I changed the above program so that it had nine String literal constants, and no Dictionary collection was used by the compiler. It seems that VB.NET lacks the String Dictionary optimization for String Switch constructs. Therefore, if you have to match a lot of string literals, building a Dictionary might be faster.

String Switch Examples Dictionary Examples

Summary

The VB.NET programming language

We looked at the Select Case statement with String arguments in the VB.NET language. This construct, in the .NET Framework 4.0, lacks the optimizations present in the C# compiler and instead compiles to a series of string comparisons. You can use non-constant Case expressions as well, but the Select Case statement really provides no advantage over a series of If statements.

VB.NET Tutorials
.NET