Search code examples
vb.netselectif-statementlanguage-features

In VB.NET why should I use Select, instead of If?


I've recently graduated and started a real job. In our training they've been exposing us to VB.NET and a lot of the features they use here. In some of the examples, they've used Select statements (and in a few places they were used where an If/Else really should have been used).

The only time that I've used a switch/select statement in other languages (other than assignments that required it) has been when I wanted the fall through to the next statement.

Given than VB.NET has no fall through, what (if any) cases are there to use the Select statement? Are there any cases when it provides advantages over and If/ElseIf statement?


Solution

  • Select Case, not just Select.
    To me, it's one of the best features of the language.

    1. It's much more visual when you have several possible values to test against.

      select case some_var
      case 1
        something()
      case 2
        something_else()
      case 3
        etc()
      end select
      
    2. It's much more readable when it comes to testing ranges:

      select case some_var
      case 1 to 10
        something()
      case 20 to 30
        something_else()
      case is > 100
        etc()
      end select
      
    3. It's much more readable when you have a bunch of more complex conditions to test, making sure only one is selected:

      select case true
      case string.isnullorempty(a_string)
        something()
      case a_string.length < 5
        something_else()
      case a_string = b_string
        etc()
      end select
      
    4. It's superior to C/C++ switch in the sense that it allows expressions as branching points, not just constants.

    5. When using constants as branching points (example 1), compiler is able to generate a more optimised code with direct jumps.