1

In VB.NET, how can I achieve the following logic?

Select Case testString
    Case Contains("ABC") : Debug.Print "ABC"
    Case Contains("XYZ") : Debug.Print "XYZ"
    Case Else : Debug.Print "Other"
End Select
CJ7
  • 22,579
  • 65
  • 193
  • 321

2 Answers2

4

Simply:

If testString.Contains("ABC") Then
    Debug.Print "ABC"
ElseIf testString.Contains("XYZ") Then
    Debug.Print "XYZ"
Else
    Debug.Print "Other"
End If

You cannot check this kind of function results in a Select Case statement, so using a simple If statement is your best and easier choice.

You can always do this:

Select Case True
    Case testString.Contains("ABC") : Debug.Print("ABC")
    Case testString.Contains("XYZ") : Debug.Print("XYZ")
    Case Else : Debug.Print("Other")
End Select

But it would work only in very concrete cases and is not very clear and necessary at all.

SysDragon
  • 9,692
  • 15
  • 60
  • 89
3

In VB.NET you could use this Select:

Select Case True
    Case testString.Contains("ABC")
        Debug.Print("ABC")
    Case testString.Contains("XYZ")
        Debug.Print("XYZ")
    Case Else : Debug.Print("Other")
End Select

However, in this case i would prefer a simple If clause.

If testString.Contains("ABC") Then
    Debug.Print("ABC")
ElseIf testString.Contains("XYZ") Then
    debug.Print("XYZ")
Else
    Debug.Print("Other")
End If

This would be clearer and also compatible with C#. switch allows only constant expressions.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Since this works in this concrete example, it will not be a valid approach for functions which returns values different than just a Boolean type always. – SysDragon Jul 09 '13 at 07:07
  • @SysDragon: Of course you can not use `Select...Case` for everything. But in more cases than in C#. OP wants to use it with a function that returns `Boolean` anyway. – Tim Schmelter Jul 09 '13 at 07:14