Enumerated Type Formatting


Visual Basic provides special formatting capabilities that can display the values of enumerated variables. For example, consider the following code:

  Private Enum Dessert     Cake = 1     Pie = 2     Cookie = 3     IceCream = 4 End Enum ... Dim dessert_choice As Dessert = Dessert.Cake MessageBox.Show(dessert_choice.ToString) 

This code displays the string Cake.

For variables of an enumerated type such as dessert_choice, the ToString method can take a specifier that determines how the value is formatted.

The specifier G or g formats the value as a string if possible. If the value is not a valid entry in the Enum’s definition, the result is the variable’s numeric value. For example, the previous code does not define a Dessert enumeration for the value 7 so, if you set dessert_choice to 7, then dessert_ choice.ToString(“G”) returns the value 7.

If you define an enumerated type with the Flags attribute, variables of that type can be a combination of the Enum’s values, as shown in the following code:

  <Flags()> _ Private Enum Dessert     Cake = 1     Pie = 2     Cookie = 4     IceCream = 8 End Enum ... Dim dessert_choice As Dessert = Dessert.IceCream Or Dessert.Cake MessageBox.Show(dessert_choice.ToString("G")) 

In this case, the G format specifier returns a string that contains all of the flag values separated by commas. In this example, the result is Cake, IceCream. Note that the values are returned in the order in which they are defined by the enumeration, not the order in which they are assigned to the variable.

If you do not use the Flags attribute when defining an enumerated type, the G format specifier always returns the variable’s numeric value if it is a combination of values rather than a single value from the list. On the other hand, the F specifier returns a list of comma-separated values if it makes sense. If you omit the Flags attribute from the previous code, dessert_choice.ToString(“G”) would return 9, but dessert_choice.ToString(“F”) would return “Cake, IceCream.”

The D or d specifier always formats the variable as a number.

The specifier X or x formats the value as a hexadecimal number.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

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