Select Case

Another way to evaluate expressions and run code based on them is the often under-utilized Select Case structure. It allows you to test for multiple values of a variable in a clean, easy to understand structure, then run blocks of code depending on those values. Here's an example of a Select Case structure:

Select Case intOrderStatus

Case 1, 2

'fascinating code for status

1 or

2

Case 3

'riveting code for status 3

Case Else

'hmm, it's some other value,

just

handle it

End Select

Notice that there is no need for nested and indented If statements, and each Case block of code doesn't need a beginning or ending statement. Just to show the difference, the equivalent code using plain old If statements looks like this:

If intOrderStatus = 1 Or intOrderStatus =

2 Then

'fascinating code for status 1 or 2

Else

If intOrderStatus = 3 Then

'riveting code for status 3

Else

'hmm, it's some other value, just

handle it

End If

Endif

This code is harder to read and understand. If you need to choose among multiple blocks of code depending on an expression's value, then Select Case is the preferred method.

0 0

Post a comment