The Select Case Statement

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes how to write a Select Case statement for multiple selection.

Beside the if statement there is another conditional statement which is Select Case.

It is a powerful and easy-to-use technique for making a decision from several options.

Actually the Select Case statement is nothing but an instance of the If Then ElseIf structure.

I would suggest using of Select Case whenever you have more than three else if statements.

In a Select Case statement, every case has its own block.

Dim intDay As Integer = 4
Dim strDay As String = String.Empty
Select Case intDay 
    Case 1 
        strDay = "Sunday" 
    Case 2 
        strDay = "Monday" 
    Case 3 
        strDay = "Tuesday" 
    Case 4 
        strDay = "Wednesday" 
    Case 5 
        strDay = "Thursday" 
    Case 6 
        strDay = "Friday" 
    Case 7 
        strDay = "Saturday" 
    Else
        strDay = "There is no such day"
End Select Console.Write(strDay) ' = Wednesday
            
As you see Select Case provides more compact and more elegant code than multiple nested if statements.
        Dim intDay As Integer = 4
        Dim strDay As String = String.Empty
        If intDay = 1 Then
            strDay = "Sunday" 
        ElseIf intDay = 2 Then
            strDay = "Monday" 
        ElseIf intDay = 3 
            strDay = "Tuesday" 
        ElseIf intDay = 4 
            strDay = "Wednesday" 
        ElseIf intDay = 5 
            strDay = "Thursday" 
        ElseIf intDay = 6 
            strDay = "Friday" 
        ElseIf intDay = 7 
            strDay = "Saturday"
        Else
            strDay = "There is no such day" 
        End If         Console.Write(strDay) ' = Wednesday
    
Previous Lesson | Next Lesson


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.