Enumerated Constants


Recall the discussion from the previous chapter about constants and the advantages of representing a single constant number like 3.1415… with the name Pi. Sometimes, we need to represent a finite set of related constants all known prior to the compilation of the program. Examples could be the days of the week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} or the months of the year { January, February, March, and so on} . Enumerators are useful for creating symbolic constants representing those values.

For example, if you want to represent the five colors just mentioned, you can declare Color to be an enumeration with the five colors Green, Blue, Red, Yellow and Purple. In C#, you express this with the following declaration statement:


The enum keyword here specifies the following:

  • Color is the name of a new custom-made type. It is called an enumeration, just like the Elevator from our elevator simulation is a custom-made type called a class.

  • By using the dot . operator, Color.Green is a symbolic constant for the int value 0, Color.Blue is a symbolic constant for the int value 1, Color.Red is a symbolic constant for the int value 2…. These symbolic constants are called enumerators or members of the enumeration.

int values counting from 0 and up by increments of 1 (0, 1, 2, and so on) are assigned to the enumeration members by default. It is possible to override these defaults by explicitly specifying the underlying type for all values represented by the enumeration, and by stating the value of each member. Members without an explicitly stated value will be assigned default values by counting up from the previous value in increments of 1. For example, by writing

 enum Color : byte { Green = 10, Blue, Red = 20, Yellow, Purple} 

Color.Green is set to represent the value 10, Color.Blue the value 11, Color.Red the value 20, Color.Yellow the value 21, and Color.Purple the value 22; all values being of type byte.

An enumerated type specifies a finite set of named numeric constants that are known at compile time.

Syntax Box 7.6 The Enumeration Declaration

 Enumeration_Declaration::=           [<Access_modifier>] enum <Enum_Name> [: <Integer_Type>] {< graphics/ccc.gifEnum_Member_Name1> [= <Integer_Value1>] [,<Enum_Member_Name2> [=  graphics/ccc.gif<Integer_ Value2>] ]... } 


 Access_modifier                  ::= public                  ::= private                  ::= protected                  ::= internal                  ::= protected internal 


  • <Integer_Type> can be any of the integer types (byte, sbyte, short, ushort, int, uint, long, and ulong).

  • The keyword enum is an alias for System.Enum.

  • Only the access modifiers public and private have been discussed so far. You can ignore the other three for the moment.

Having specified the enumeration, it is possible to declare a variable of that type. For example

 Color wall; 

declares wall to be of type Color. wall can now hold any of the five enumerators Color.Green, Color.Blue, and so on. Consequently, it is possible to perform the following assignment:

 wall = Color.Red; 

Notice that only the five enumerator values can validly be assigned to wall. As a result, even though Color.Red has the value 20 in this example, it is not possible to assign 20 to wall, as attempted in the following:


This will trigger a compiler error.

Improve the Readability with Enumerated Types


Languages that do not have the enumerator feature often rely on error-prone and unclear schemes for representing groups of constants. For instance, to represent the five colors mentioned in our example, an often used procedure is to say, "1 stands for green, 2 stands for red, 3 stands for blue, and so on." In this case, a check for whether the color of wall is green by using an if statement would require you to write the following:


instead of


The latter is much clearer and can intuitively be understood without any accompanying comments.

In conclusion, to improve the clarity and self-documenting abilities of your source code, use enumerations when you know all the possible values of a variable before the program is compiled.

Listing 7.5 provides an example of an enumerator representing the days of the week. The program simply moves through the days of the week. Whenever the current day is a Thursday or a Sunday, the program announces that fact.

Listing 7.5 Source Code for EnumDayCounter.cs
01: using System; 02: 03: enum Day { Monday, Tuesday, Wednesday, 04:     Thursday, Friday, Saturday, Sunday} 05: 06: public class SimpleDayCounter 07: { 08:     public static void Main() 09:     { 10:         Day currentDay = Day.Monday; 11:         int counter = 1; 12:         while (counter < 8) 13:         { 14:             Console.WriteLine(counter); 15:             if(currentDay == Day.Thursday) 16:                 Console.WriteLine("\tIt's Thursday"); 17:             if(currentDay == Day.Sunday) 18:                 Console.WriteLine("\tIt's Sunday"); 19:             counter++; 20:             currentDay++; 21:         } 22:     } 23: } 1 2 3 4       It's Thursday 5 6 7       It's Sunday 

Lines 3 and 4 define the enumerated type Day to have seven members, ranging from Day.Monday representing 0 to Day.Sunday representing 6.

The Main() method of the class SimpleDayCounter contains a while loop. It will repeat itself seven times because of

  • Line 11, where counter is set to 1

  • Line 12, where the loop only is repeated if the condition (counter < 8) is true

  • Line 19, which increments counter by 1 every time the loop is repeated

Line 10 declares currentDay to be of type Day and assigns it the enumerator value Day.Monday.

Line 15 checks whether currentDay is equal to Day.Thursday. If this is the case, "It's Thursday" is printed onscreen by line 16. Similarly, if currentDay is equal to Day.Sunday, line 18 prints "It's Sunday" onscreen.

Line 20 illustrates our ability to use the increment operator ++ to increment the value of currentDay by 1. If currentDay prior to applying the ++ operator is holding the value Day.Monday that is equal to 0, currentDay will have the value 1 after applying the ++ operator. Because 1 is represented by Day.Tuesday, currentDay will now hold this enumerator.



The increment operator does not look for the next enumerator in the list, but merely increments the integer value by 1 of the variable (in this case, currentDay) of which it is applied. The increment operator ++ is only suitable in Listing 7.5 because the enumerators (days) represent a sequence of numbers, all with increments of 1.

Enumerated Types Make It Easier to Modify Your Source Code


Not only does the dubious scheme mentioned in the previous Tip box (0 stands for Monday; 1 stands for Tuesday, and so on.) produce unclear code, it also generates source code that is difficult to modify.

For example, there happens to be 8 days in a week on planet Blipos. The additional day is between Tuesday and Wednesday called Cosday, so their week looks like { Monday, Tuesday, Cosday, Wednesday, Thursday, Friday, Saturday, Sunday} . Imagine if we wanted to convert our day counting program to be useful on planet Blipos. Had we not used enumerators in Listing 7.5 but, instead, followed the dubious scheme (0 is for Monday, and so on) mentioned earlier, we would be forced to change all the 2s representing Wednesdays to 3s, all the 3s representing Thursdays to 4s, and so on to let 2 represent Cosday. Alternately, we could have let 7 represent Cosday to avoid all the changes, but this would lead to a very confusing program. Most programmers would expect Cosday to be represented by number 2.

On the other hand, if we had to make a similar modification to our enumerator-based source code of Listing 7.5, we would need to make only one single modification in the definition of Day, as follows:

 03:    enum Day { Monday, Tuesday, Cosday, Wednesday, 04:        Thursday, Friday, Saturday, Sunday} 


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net