Declaring Enumerations

Unlike the variables discussed thus far, an enumeration is not a type in itself but a special form of a value type. An enumeration is derived from System.Enum and supplies names for values. The underlying type that an enumeration represents must be a byte, short, int, or long. Each field within an enumeration is static and represents a constant.

To declare an enumeration, you must provide the keyword enum followed by the name of the enumeration. Then you must provide an opening bracket followed by a list of the enumeration strings, and end with a closing bracket, as shown in the following example:

public enum Pizza {

Supreme, MeatLovers, CheeseLovers, Vegetable,

This code creates an enumeration called Pizza. The pizza enumeration contains four different name/value pairs describing different kinds of pizza, but no values are defined. When you declare an enumeration, the first name you declare takes on the value of 1. The second name listed takes on the value of 1, and so on. You can override this functionality by assigning a value to each name, as shown here:

public enum Pizza {

MeatLovers = 3, CheeseLovers = 4, Vegetable = 5,

The value of each enumeration field has been incremented by 1. Not all of this code is necessary, though. By assigning Supreme a value of 2, the following fields follow in sequence. Therefore, you can remove the assignments to MeatLovers, CheeseLovers, and Vegetable.

Enumerators can be referenced in one of two ways. You can program around their field names or you can program around their values. As an example, you can assign the field name to a string variable with the following code:

string MyString = Pizza.Supreme;

You might also want to reference the value of a field. You can accomplish this by explicit typecasting. For example, you can retrieve the value of the Supreme field with the following code:

int MyInteger = (int)Pizza.Supreme;

0 0

Post a comment