Select Case Statement in Visual Basic 2008
An alternative to the efficient but difficult-to-read code of the multiple ElseIf structure is the Select Case structure, which compares the same expression to different values. The advantage of the Select Case statement over multiple If. . .Then. . .ElseIf statements is that it makes the code easier to read and maintain.
The Select Case structure evaluates a single expression at the top of the structure. The result of the expression is then compared with several values; if it matches one of them, the corresponding block of statements is executed. Here's the syntax of the Select Case statement:
A practical example based on the Select Case statement is shown in Listing 3.2.
Listing 3.2: Using the Select Case Statement
In the listing, the expression that's evaluated at the beginning of the statement is the Now.DayOfWeek method. This method returns a member of the DayOfWeek enumeration, and you can use the names of these members in your code to make it easier to read. The value of this expression is compared with the values that follow each Case keyword. If they match, the block of statements up to the next Case keyword is executed, and the program skips to the statement following the End Select statement. The block of the Case Else statement is optional, and is executed if none of the previous cases matches the expression. The first two Case statements take care of Fridays and Mondays, and the Case Else statement takes care of the other days.
Some Case statements can be followed by multiple values, which are separated by commas. Listing 3.3 is a revised version of the previous example.
Listing 3.3: A Select Case StatementwithMultiple Cases per Clause
Monday, weekends, and weekdays are handled separately by three Case statements. The second Case statement handles multiple values (all workdays except for Monday and Friday). Monday is handled by a separate Case statement. This structure doesn't contain a Case Else statement because all possible values are examined in the Case statements; the DayOfWeek method can't return another value.
The Case statements can get a little more complex. For example, you may want to distinguish a case where the variable is larger (or smaller) than a value. To implement this logic, use the Is keyword, as in the following code segment that distinguishes between the first and second half of the month:
Table of Contents
W3computing.com Copyright 2011 © All Rights Reserved
|Home | Useful links | Contact us|