
.NET 1.1+Formatting Enumeration Constants
Enumerations provide useful groupings of named, numeric constants that can enhance the readability of source code. When the constants need to be outputted they may be formatted as numbers or strings, with various available options.
Enumerations
C# provides two types of enumeration. Standard enumerations contain a list of discrete, named integer values. Variables can be declared using the type of the enumeration and their values can be set using the appropriate name or an integer value. Using names instead of simple numbers can greatly increase the maintainability of code. Bit field enumerations also contain named integers but allow the values to be combined using logical bitwise operators.
An example of a standard enumeration is a type that provides twelve constants representing the months of the year. January may be month zero, February would be month one and so on. These values cannot logically be combined. An example bit field enumeration could represent the various states of a printer with values representing an empty paper tray, an exhausted toner cartridge or a paper jam. Some of these states can be combined, for example, allowing a single value to represent a paper with no toner or paper present.
The code for the above two enumerations, which we will use in the code samples for this article, is as follows:
enum Month
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
[Flags]
enum PrinterStatus
{
OK = 0,
OffLine = 1,
PaperTrayEmpty = 2,
TonerExhausted = 4,
PaperJam = 8
}
ToString Method
The ToString method is common to all .NET framework types. It allows a value to be converted to a string representation. When applied to enumerations, the ToString method, used without arguments, returns a string containing the name of one or more constants wherever possible. However, if the source variable cannot be represented by a defined name, the numeric value is returned as a string.
We can see this by creating some instances of our two test enumerated types and outputting the results of the ToString method:
Month jan = Month.January;
Month month13 = (Month)13;
PrinterStatus allOK = PrinterStatus.OK;
PrinterStatus twoProblems = PrinterStatus.PaperTrayEmpty | PrinterStatus.TonerExhausted;
PrinterStatus unknownStatus = PrinterStatus.TonerExhausted | (PrinterStatus)16;
Console.WriteLine(jan.ToString()); // January
Console.WriteLine(month13.ToString()); // 13
Console.WriteLine(allOK.ToString()); // OK
Console.WriteLine(twoProblems.ToString()); // PaperTrayEmpty, TonerExhausted
Console.WriteLine(unknownStatus.ToString()); // 20
13 December 2011