7

Is there a way to use the Select Case statment in VB.net for beginswith? Or do i have to use a long elseif? Example:

If text.StartsWith("/go") then
elseif test.StartsWith("/stop")
elseif test.StartsWith("/continue")
End If

But instead something like:

Select Case text
Case text.StartsWith("/go")
Case text.StartsWith("/stop")
Case text.StartsWith("/continue")
Case Else
End Select
End Sub
James T
  • 3,292
  • 8
  • 40
  • 70
  • "Or do i have to use a long elseif" what is long about elseif compared to case? One more character. OK you need the Then at the end of condition but VS will add that for you so not extra typing on your part. – Tim Murphy Sep 23 '10 at 09:27
  • The Case True answers probably work but it seems like code smell to me. What does it achieve? – Tim Murphy Sep 23 '10 at 09:29
  • I think it is easier to read. – James T Sep 23 '10 at 12:28
  • I tend to agree that it's easier to read. `Select Case` implies to me that there's one thing you're checking for a number of mutually exclusive states. That seems to make it appropriate here; the one thing you're checking is the start of the word. (Though it'd be less questionable if you could *get* the start of the string, so you could test it the way mortals expect.) – cHao May 01 '13 at 14:24
  • What comes after this command in the string? If it is for example a space, you can get everything up to that space, and use in the select. – Guffa Sep 22 '10 at 19:38

2 Answers2

11

You can do something like

Select Case True
    Case text.StartsWith("/go")
        ...
    Case text.StartsWith("/stop")
        ...
    Case Else
End Select
cHao
  • 84,970
  • 20
  • 145
  • 172
4
Select Case True
 Case text.startswith("/go") :  messagebox.show("Go")
 Case text.startswith("/stop") :   messagebox.show("stop")
 Case text.startswith("/continue") :   messagebox.show("continue")
End Select
Kamyar
  • 18,639
  • 9
  • 97
  • 171