16

In C I can assign default to some existing switch entry:

switch(c) {

default :
case 1:

       break;

case 2 :


      break;   

}

Is there a similar possibility in VB's select statement?

Kara
  • 6,115
  • 16
  • 50
  • 57
user1797147
  • 915
  • 3
  • 14
  • 33

2 Answers2

25

use case Else , it is same as default of c syntax:

Select [ Case ] testexpression
    [ Case expressionlist
        [ statements ] ]
    [ Case Else
        [ elsestatements ] ]
End Select

e.g.

creamcake = TextBox1.Text

Select Case creamcake

Case "Eaten"
DietState = "Diet Ruined"
Case "Not Eaten"
DietState = "Diet Not Ruined"
Case Else
DietState = "Didn't check"
End Select

if you want to assign more than one case then example

Select Case agerange

Case 16 To 21
MsgBox “Still Young”
Case 50 To 64
MsgBox “Start Lying”

End Select
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70
  • ok, I noticed that but I want "case else" entry to be assigned to the same code as "case Easten" in your example. This is possible ? – user1797147 Dec 05 '12 at 09:58
  • @user1797147: if u want to use with Else then just don't use case"eaten" .just remove it, it automatically goes to else part – Ravindra Bagale Dec 05 '12 at 10:03
  • so in VB if no "case else" will just fall in the first entry ? – user1797147 Dec 05 '12 at 10:06
  • 1
    I was looking for the same thing. What we have here is basically just a syntax preference. Sure, if you just omit "eaten" it will just fall into the Else part. But for clarity, if you want someone else who is working on your code to read that it is intentional behaviour that "eaten" falls into the Else part, then a syntax like ` Case "Eaten", Else` would be useful. In my case I solved this by letting "Eaten" fall into the Else part and adding one line of comment ` ' Case "Eaten"` so that anyone reading it will notice that it is intentional that "Eaten" should be treated as Else – Koert van Kleef Feb 07 '14 at 10:03
1
Select Object.Name.ToString()
    Case "Name1"
        'Do something
    Case "Name2"
        'Do something else
    Case Else
        'Do the default action
End Select

This question is the exact opposite of VB.NET Select...Case Statement Equivalent in C#

Community
  • 1
  • 1
LonWolf
  • 132
  • 4