Switch in Visual Basic .NET

Switch statements express conditionals across many branches.

Here’s a basic switch.

Imports System
Imports System.DateTime

Module Program
    Sub Main()
        Dim i As Integer = 2
        Console.Write("Write {0} as ", i)
        Select Case i
            Case 1
                Console.WriteLine("one")
            Case 2
                Console.WriteLine("two")
            Case 3
                Console.WriteLine("three")
        End Select

        ' You can use commas to separate multiple expressions in the same case statement.
        ' We use the optional default case in this example as well.
        Select Case DateTime.Now.DayOfWeek
            Case DayOfWeek.Saturday, DayOfWeek.Sunday
                Console.WriteLine("It's the weekend")
            Case Else
                Console.WriteLine("It's a weekday")
        End Select

        ' switch without an expression is an alternate way to express if/else logic.
        Dim t As DateTime = DateTime.Now
        Select Case True
            Case t.Hour < 12
                Console.WriteLine("It's before noon")
            Case Else
                Console.WriteLine("It's after noon")
        End Select

        ' A type switch compares types instead of values.
        Dim whatAmI As Action(Of Object) = Sub(i As Object)
                                               Select Case i.GetType()
                                                   Case GetType(Boolean)
                                                       Console.WriteLine("I'm a bool")
                                                   Case GetType(Integer)
                                                       Console.WriteLine("I'm an int")
                                                   Case Else
                                                       Console.WriteLine("Don't know type {0}", i.GetType().Name)
                                               End Select
                                           End Sub
        whatAmI(True)
        whatAmI(1)
        whatAmI("hey")
    End Sub
End Module

As you can see, the Select Case statements in Visual Basic .NET allow for similar functionality as switch statements in other languages. They enable branching logic based on the value of a variable, multiple expressions per case, and even type-checking for objects.