
.NET 1.1+C# Constants and Enumerations (2)
The forty-eighth part of the C# Fundamentals tutorial examines the use of constants and enumerations. These provide two methods of describing non-changing values using descriptive words rather than "magic numbers" to improve code readability.
Enumerations
An enumeration, or enumerator list, declares a series of related constants, each with an integer value. Enumerations are useful for defining sequences and states, particularly when there is a natural progression through those states. This is because each constant in the list can be formatted and compared using either its name or value.
Defining an Enumeration
The simplest method for declaring an enumeration is to list all of the possible names in a set of braces after the enumeration's name. To indicate that an enumerator list is being defined, the enum keyword is used as a prefix to the name. In this case, the first item in the list is assigned the value zero and each subsequent item is incremented.
This simple declaration defines a constant for every month of the year:
enum Month { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
Using Enumerated Values
Once an enumeration is declared within a class, all of the methods of the class are able to utilise the values of the list using the names of the list and of the individual item separated using the member access operator (.) The following example shows how a value from the list can be retrieved and outputted as either an integer value or as a string.
NB: Enumerations can be declared with wider scopes to allow their use in multiple classes.
class Program
{
enum Month { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
static void Main(string[] args)
{
Console.WriteLine((int)Month.Feb); // Outputs "1"
Console.WriteLine(Month.Feb); // Outputs "Feb"
}
}
As the enumeration provides a list of linked numeric values, it is possible to perform simple operations on the integer representations. In the next sample, a variable is declared of the enumerated type. Mathematical operators are then used to modify the value. Note that when the range of the enumeration is exceeded, the values revert back to the integer representations.
class Program
{
enum Month { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
static void Main(string[] args)
{
Month mon = Month.Jan;
for (int i = 0; i<=12; i++)
{
Console.WriteLine(mon++);
}
}
}
/* OUTPUT
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
12
*/
16 August 2007