Enumerations: Making Select Case Blocks Easier to Understand


Enumerations: Making Select Case Blocks Easier to Understand

Listing 11.3 presents a Select Case statement block for the processing of a days-of-the-week type of programming problem. The comments help the reader understand what the code is doing, but you can make it even more understandable by using Visual Basic .NET's enumeration statement. The enumeration statement allows you to define a set of named constants for use in a program. This is the syntax of the Enum statement:

 [AccessSpecifier] Enum EnumName [As Type]    ' List of Enum members End Enum 

If AccessSpecifier is not supplied, it is Public by default, but it can have other access types as well. (You will learn more about access specifiers in Chapter 15, "Encapsulation.") If you elect to specify the type of data by using the As keyword, the data types are limited to Byte , Integer , Long , and Short . If you do not specify the type, the enumeration members are Integer by default. The scope for enumerations is limited to the module, namespace, and assembly levels. This means that enumerations cannot be defined with local scope.

Consider the following example:

 Enum ThisDay    Monday = 1   Tuesday = 2   Wednesday = 3   Thursday = 4   Friday = 5   Saturday = 6   Sunday = 7 End Enum 

The members of the ThisDay enumeration are simply named constants for each day. This definition would appear near the top of the Class code, after the Inherits statement. Note that you can use the constants in expressions, but you cannot change their values in any way after they are initialized in the Enum statement block.

You can now rewrite Listing 11.3 as Listing 11.4.

Listing 11.4 Using Enumerations in a Select Case Statement Block
 Select ThisDay   Case ThisDay.Monday     TakeHeadacheMedicine()   Case ThisDay.Tuesday     GroceryShop()   Case ThisDay.Wednesday     PayBills()   Case ThisDay.Thursday     PayMoreBills()   Case ThisDay.Friday     LeagueNight()   Case ThisDay.Saturday     Bathe()   Case ThisDay.Sunday     Rest()   Case Else  ' Catch-all     MessageBox.Show("Improper value for MyDay") End Select 

Even though the change from Listing 11.3 to Listing 11.4 has no real impact on the performance of the code, the use of enumerations makes it easier to understand what the code is doing. This is especially true when comments are missing.



Visual Basic .NET. Primer Plus
Visual Basic .NET Primer Plus
ISBN: 0672324857
EAN: 2147483647
Year: 2003
Pages: 238
Authors: Jack Purdum

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net