JScript .NET, Part II: Major Features

Variable Enumeration

Enumeration is also common to many other programming languages. Enumeration associates a symbolic name with a set of predefined discrete values. Enumeration is very powerful in making your application a lot easier to maintain. Enumerated variables can only assume values out of the predefined set. As in other programming languages, you define an enumerated data type with the enum statement. The following enum statement enumerates the major TV networks in the US:

enum tvNetworkType {
ABC,
CBS,
NBC,
FOX
}

When you define a variable of type tvNetworkType, it can assume only one of the four values above: ABC, CBS, NBC, and FOX. Let's declare such a variable:

var myFavoriteStation : tvNetworkType;

Let's assign it now the value of ABC:

myFavoriteStation = tvNetworkType.ABC;

Symbolic names you declare within the enum statement are numbered sequentially, starting at zero. In the example above:

ABC = 0;
CBS = 1;
NBC = 2;
FOX = 3;

You can declare the underlying type to be any integral data type, i.e. one of the following: int, short, long, byte, uint, ushort, ulong, or sbyte.

By default, the underlying data type of an enumeration is int. To save space, you can declare the underlying type of tvNetworkType to be of type byte:

enum tvNetworkType : byte {
ABC,
CBS,
NBC,
FOX
}

By default, the first member is initialized as zero. You can change it by setting its value explicitly. For example, you can decide that ABC should be equal to 1 instead of zero:

enum tvNetworkType : byte {
ABC = 1,
CBS,
NBC,
FOX
}

You can initialize any member of the enumerated type. By default, each member is one more than the previous member, if not explicitly initialized. In the above example, CBS is 2, NBC is 3, and FOX is 4. You can initialize all of them as follows:

enum tvNetworkType : byte {
ABC = 1,
CBS = 2,
NBC = 4,
FOX = 8
}

An enum value is accessed as an object member. The name of the member should be prefixed by the name of the enumeration, for example tvNetworkType.ABC. When you assign a value to an enumerated variable, you can use a full name (such as tvNetworkType.ABC), a string representation of the name ("ABC"), or a numeric value (1).

When you use a string that is known at compile time, the compiler will perform the necessary conversion. For example, "ABC" would be replaced by tvNetworkType.ABC. If the string is not known at compile time, a conversion will be made at run time. That conversion may fail if the string is not a valid member of the enumerated type. It's a good practice to avoid run-time assignments of enumerated variables. It takes precious CPU time, and it may end up in an error.

An enumerated variable can assume values outside the range of its declared values. This is convenient if you want to combine two values to create a third one which is not defined as a member. The following line demonstrates a combination of the members NBC and FOX: