Select Case (Switch Statement, VB.NET)
This page was last reviewed on Dec 7, 2021.
Dot Net Perls
Select case. The C# language has no "select case" statement. But this idea of a special construct where constants can be selected is implemented with the "switch" keyword.
For many programs, we can convert a select-case statement easily to a switch statement. Cases cannot be stacked (on separate lines) in VB.NET, unlike in C#. This is important.
Switch example. This example program uses a switch statement. We have three "case" blocks and a default block. The cases 100 and 1000 share the same code.
Result The value int is equal to 100. So we end up matching the "case 100" statement, and the letter "B" is displayed.
using System; class Program { static void Main() { int value = 100; switch (value) { case 10: Console.WriteLine("A"); break; case 100: case 1000: // Two cases stacked on each other. Console.WriteLine("B"); break; default: // Default case. Console.WriteLine("DEFAULT"); break; } } }
Select case example. Here is the equivalent "select case" example in VB.NET. Note how we use the "Select" keyword, and the cases 100 and 1000 must be specified on the same line.
Detail The default case is "Case Else." This makes some logical sense, but does not read well in English.
Module Module1 Sub Main() Dim value As Integer = 100 Select Case value Case 10 Console.WriteLine("A") Case 100, 1000 ' Two cases stacked on one line. ' ... You cannot put each on a separate line. Console.WriteLine("B") Case Else ' Default case. Console.WriteLine("DEFAULT CASE") End Select End Sub End Module
Some final notes. With C# we invoke the "switch statement" instead of a "select case" statement. The implementation (to some extent, with the exclusion of string switches) is shared.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 7, 2021 (edit link).
© 2007-2024 Sam Allen.