Formatting Enumerations


C# allows you to format the values defined by an enumeration. In general, enumeration values can be displayed using their name or their value. The enumeration format specifiers are shown in Table 21-9. Pay special attention to the G and F formats. Enumerations that will be used to represent bit-fields can be preceded by the Flags attribute. Typically, bitfields hold values that represent individual bits and are arranged in powers of two. If the Flags attribute is present, then the G specifier will display the names of all of the values that comprise the value, assuming the value is valid. The F specifier will display the names of all of the values that comprise the value if the value can be constructed by adding together two or more fields defined by the enumeration.

Table 21-9: The Enumeration Format Specifiers

Specifier

Meaning

D

Displays the value as a decimal integer.

d

Same as D.

F

Displays the name of the value. However, if the value can be created by adding together two or more values defined by the enumeration, then the names of each part of the value will be displayed. This applies whether or not the Flags attribute has been specified.

f

Same as F.

G

Displays the name of the value. If the enumeration is preceded by the Flags attribute, then all names that are part of the value will be displayed (assuming a valid value).

g

Same as G.

X

Displays the value as a hexadecimal integer. Leading zeros will be added to ensure that at least eight digits are shown.

x

Same as X.

The following program demonstrates the enumeration specifiers:

 // Format an enumeration. using System; class EnumFmtDemo {   enum Direction { North, South, East, West }   [Flags] enum Status { Ready=0x1, OffLine=0x2,                         Waiting=0x4, TransmitOK=0x8,                         ReceiveOK=0x10, OnLine=0x20 }   public static void Main() {     Direction d = Direction.West;     Console.WriteLine("{0:G}", d);     Console.WriteLine("{0:F}", d);     Console.WriteLine("{0:D}", d);     Console.WriteLine("{0:X}", d);     Status s = Status.Ready | Status.TransmitOK;     Console.WriteLine("{0:G}", s);     Console.WriteLine("{0:F}", s);     Console.WriteLine("{0:D}", s);     Console.WriteLine("{0:X}", s);   } }

The output is shown here:

 West West 3 00000003 Ready, TransmitOK Ready, TransmitOK 9 00000009




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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