Enumerations


An enumeration is a set of named integer constants. The keyword enum declares an enumerated type. The general form for an enumeration is Here, the type name of the enumeration is specified by name. The enumeration list is a comma-separated list of identifiers.

 enum name { enumeration list };

Here is an example. The following code fragment defines an enumeration called Apple that enumerates various types of apples:

 enum Apple { Jonathan, GoldenDel, RedDel, Winesap,              Cortland, McIntosh };

A key point to understand about an enumeration is that each of the symbols stands for an integer value, with each symbol given a value one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. Thus, Jonathan has the value 0, GoldenDel has the value 1, and so on.

An enumeration constant can be used anywhere that an integer may be used. However, no implicit conversions are defined between an enum type and the built-in integer types, so an explicit cast must be used. Also, a cast must be used when converting between two enumeration types.

The members of an enumeration are accessed through their type name via the dot operator. For example,

 Console.WriteLine(Apple.RedDel + " has the value " +                   (int)Apple.RedDel);

displays

 RedDel has the value 2

As the output shows, when an enumerated value is displayed, its name is used. To obtain its integer value, a cast to int must be used.

Here is a program that illustrates the Apple enumeration:

 // Demonstrate an enumeration. using System; class EnumDemo {   enum Apple { Jonathan, GoldenDel, RedDel, Winesap,                Cortland, McIntosh };   public static void Main() {     string[] color = {       "Red",       "Yellow",       "Red",       "Red",       "Red",       "Reddish Green"     };     Apple i; // declare an enum variable     // use i to cycle through the enum     for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)       Console.WriteLine(i + " has value of " + (int)i);     Console.WriteLine();     // use an enumeration to index an array     for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)       Console.WriteLine("Color of " + i + " is " +                          color[(int)i]);   } }

The output from the program is shown here:

 Jonathan has value of 0 GoldenDel has value of 1 RedDel has value of 2 Winesap has value of 3 Cortland has value of 4 McIntosh has value of 5 Color of Jonathan is Red Color of GoldenDel is Yellow Color of RedDel is Red Color of Winesap is Red Color of Cortland is Red Color of McIntosh is Reddish Green

Notice how the for loops are controlled by a variable of type Apple. Because the enumerated values in Apple start at zero, these values can be used to index color to obtain the color of the apple. Notice that a cast is required when the enumeration value is used to index the color array. As mentioned, there are no implicit conversions defined between integers and enumeration types. An explicit cast is required.

One other point: Since enumerated values are integers, you can use an enumeration type to control a switch statement. You will see an example of this shortly.

Initialize an Enumeration

You can specify the value of one or more of the symbols by using an initializer. Do this by following the symbol with an equal sign and an integer value. Symbols that appear after initializers are assigned values greater than the previous initialization value. For example, the following code assigns the value of 10 to RedDel:

 enum Apple { Jonathan, GoldenDel, RedDel = 10, Winesap,              Cortland, McIntosh };

Now the values of these symbols are

Jonathan

0

GoldenDel

1

RedDel

10

Winesap

11

Cortland

12

McIntosh

13

Specifying the Base Type of an Enumeration

By default, enumerations are based on type int, but you can create an enumeration of any integer type, except for type char. To specify a type other than int, put the base type after the enumeration name, separated by a colon. For example, this statement makes Apple an enumeration based on byte:

 enum Apple : byte { Jonathan, GoldenDel, RedDel, Winesap,                     Cortland, McIntosh };

Now Apple.Winesap, for example, is a byte quantity.

Using Enumerations

At first glance you might think that enumerations are an interesting but relatively unimportant part of C#, yet this is not the case. Enumerations are very useful when your program requires the use of one or more specialized symbols. For example, imagine that you are writing a program that controls a conveyor belt in a factory. You might create a method called conveyor( ) that accepts the following commands as parameters: start, stop, forward, and reverse. Instead of passing conveyor( ) integers, such as 1 for start, 2 for stop, and so on, which is error-prone, you can create an enumeration that assigns words to these values. Here is an example of this approach:

 // Simulate a conveyor belt using System; class ConveyorControl {   // enumerate the conveyor commands   public enum Action { start, stop, forward, reverse };   public void conveyor(Action com) {     switch(com) {       case Action.start:         Console.WriteLine("Starting conveyor.");         break;       case Action.stop:         Console.WriteLine("Stopping conveyor.");         break;       case Action.forward:         Console.WriteLine("Moving forward.");         break;       case Action.reverse:         Console.WriteLine("Moving backward.");         break;     }   } } class ConveyorDemo {   public static void Main() {     ConveyorControl c = new ConveyorControl();     c.conveyor(ConveyorControl.Action.start);     c.conveyor(ConveyorControl.Action.forward);     c.conveyor(ConveyorControl.Action.reverse);     c.conveyor(ConveyorControl.Action.stop);   } }

The output from the program is shown here:

 Starting conveyor. Moving forward. Moving backward. Stopping conveyor.

Because conveyor( ) takes an argument of type Action, only the values defined by Action can be passed to the method. For example, here an attempt is made to pass the value 22 to conveyor( ):

 c.conveyor(22); // Error!

This won’t compile because there is no predefined conversion from int to Action. This prevents the passing of invalid commands to conveyor( ). Of course, you could use a cast to force a conversion, but this would require a premeditated act, not an accidental misuse. Also, because commands are specified by name rather than by a number, it is less likely that a user of conveyor( ) will inadvertently pass the wrong value.

There is one other point of interest in this example: notice that an enumeration type is used to control the switch statement. As mentioned, because enumerations are based on integer types, they are perfectly valid for use in a switch.




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