VB.NET Select Case Example

Select method call

You want to quickly match the value of a variable with a set of constants in your VB.NET program. The Select Case statement provides a way for you to do this: you specify the variable and the individual Cases it may have.

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

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. Here, we read a line from the Console, call Integer.Parse on it, and then Select it from a set of cases. If you type 2, you get "You typed two".

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
Integer.Parse Function Examples

Implementation and performance

The Select Case statement is implemented with the switch opcode in the intermediate language. This is the same implementation as the switch keyword from the C# language.

Note

Performance of Select Case is highly dependent on both your the cases and the data in your program. If you have 1000 cases and one is most common, the fastest thing to do would be just test for the most common one first with an If statement.

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 not very large; it might be best to just use whatever 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; its performance is dependent on several factors and may be slower or faster than If statements.

VB.NET Tutorials
.NET