Select Case Fall through with Not Condition in VB.NET

kurozakura picture kurozakura · Mar 23, 2011 · Viewed 12.4k times · Source

How to Add Not condition in the below select case.

Is <> works for single value, and 'To' works for a Range but the value are specific values there are not series of numbers. Is it possible to use select case in this scenario, or do i have to switch to if-else. Ex: i don't want case to execute when value is 0 and 3

           Select value
             case 0,1,2,3
           End Select

Answer

Cody Gray picture Cody Gray · Mar 23, 2011

I'm not sure I understand the question...

Why can't you just write the example code like so:

Select Case value
    Case 1, 2
        DoWork()
End Select

Nothing gets executed when value = 0 or value = 3. The series of values provided to a Case statement doesn't have to be sequential.


Update in response to comment:

I would write that like this, taking advantage of the Case Else label:

Select Case myComboBox.SelectedIndex
    Case 1, 5, 8
        'The suggestion is acceptable, so process it
        DoWork()
    Case Else
        'The suggestion is invalid, so show an error
        MessageBox.Show("You cannot select that option. " & _
                        "Please choose options 1, 5, or 8 instead.", _
                        "Invalid Selection", _
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
End Select

Of course, if you don't actually have any "work" to be done in the case that the user selects the correct value, there seems little point in using a Select Case statement at all. The cardinal rule should be to use whichever makes your code the clearest and easiest to understand. There's little validity to the suspicion that Select Case is faster than an If statement—the compiler is smart enough to produce virtually equivalent results in almost every case.