Choose the case when you end up with no state in VB.NET

How to add No State in the example below.

Whether <> works for a single value, and "To" works for a range, but the value is a specific value, and the row numbers are not. Is it possible to use the select script in this script, or do I need to switch to if-else. Example: I do not want the case to be executed when the value is 0 and 3

Select value case 0,1,2,3 End Select 
+4
source share
3 answers

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

Why can't you just write sample code like this:

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

Nothing happens when value = 0 or value = 3 . The number of values ​​provided to the Case statement does not have to be sequential.


Update in response to comment:

I would write this using the Case Else sign:

 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 in fact you don’t have any β€œwork” in the case when the user selects the correct value, it makes little sense to use the Select Case operator at all. The cardinal rule should be to use what makes your code the clearest and easiest to understand. It is unlikely that the Select Case faster than the If statement - the compiler is smart enough to get almost equivalent results in almost every case.

+11
source

Based on what Cody wrote, I would go with:

 Select Case value Case 1, 2 DoWork() Case 0 ,3 'nothing to do, only log if needed Case Else Debug.Fail("Please provide a logical path for all possible values") End Select 

Additional branches are just to clarify the intent of the code and protect against future changes.

+1
source

I often combine SELECT / CASE with IF / END IF. The first is to catch the range, then the second is to do similar things with the range, but maybe with slight differences.

  Dim Result As Integer = 1 Select Case Result Case 0 To 3 SaveOrder() '0 to 3 is success If Result <> 0 AndAlso Result <> 3 Then '1 and 2 = Everything ok SendCustomerMesage(0) Else '0 and 3 = Order OK, but no stock in storage SendCustomerMesage(1) End If Case 4 To 8 '4 to 8 is error InformCustomer(value) Case Else HandleError(value) End Select 
0
source

Source: https://habr.com/ru/post/1344893/


All Articles