The VB.NET Select Case statement is used on a String. With this statement we 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.
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).
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 VB.NET, you can use variables in the Case expressions. But you may lose optimizations. In Integer Select Case statements, if you use a non-constant integer, you may lose performance—the switch opcode cannot be used.Integer InformationSelect Case Exampleswitch Instruction
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 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 String Switch constructs.
Therefore:If you have to match a lot of string literals, building a Dictionary might be faster.String Switch ExamplesDictionary Examples
We looked at the Select Case statement with Strings. This construct (in .NET 4.0) lacks optimizations 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 provides no advantage over a series of If-statements.