Visual Basic and Visual FoxPro Case statements


Select Case, Case, Case Else, End Select


Do Case, Case, Otherwise, End Case

At first sight these structures look very similar but there is a deep difference between the two.

Visual Basic Syntax Notes

The cases in Visual Basic must all refer to the same variable. This variable is stated in the first line of the structure and each case merely specifies a value or a range of values for that variable. If none of these values match then the code in the Case Else clause is executed.

Select Case CustomerType
  Case 1
    Status = "Delivery is free for category 1."
  Case 3 To 5
    Status = "Delivery is £1.00 for categories 3, 4 and 5."
  Case Else
    Status = "Delivery is £10.00 for everyone else."
End Select

The variable controlling the structure can be of any text, numeric or date type.

Visual FoxPro Syntax Notes

Each case in a Visual FoxPro Do Case structure has its own independent logical test which allows for a lot more flexibility. If none of these tests evaluate as true then the code in the Otherwise clause is executed.

Do Case
  Case Price > 1000
    Status = "Delivery is free over £1,000."
  Case CustomerType >= 3 And CustomerType <= 5
    Status = "Delivery is £1.00 for categories 3, 4 and 5."
    Status = "Delivery is £10.00 for everyone else."

The conditions for each case in a Visual FoxPro Case structure can be anything that returns a boolean. There is no special syntax for a range equivalent to the "3 To 5" in VB but FoxPro has the flexibility to use an And to combine two comparisons in the statement.

Common Syntax

Only a single case will execute in the structure in both languages. Neither implements a Java style fall-through execution.

The final Case Else or Otherwise clause is optional but it's always a wise precaution to include it. Even if it just says:

     Status = "This status is not possible."

If  |  Language index  |  Loops