Lesson 7: Enumerators

 

Enumerators are numerical types limited to a restricted set of values. Their specification includes literals which can then be used as constants for the values they are set to. To illustrate such a specification, the following code declares constant values for each of the days of the week.

1.

public enum DAYS

2.

{

3.

    Monday,

4.

    Tuesday,

5.

    Wednesday,

6.

    Thursday,

7.

    Friday,

8.

    Saturday,

9.

    Sunday

10.

}


This code is affected by two default settings. Firstly, the default value type of enumerators is integer. Secondly, by default the first literal specified is set to 0 and this value is then incremented for each subsequent literal. Hence, given the above DAYS.Monday equals the integer 0 and DAYS.Sunday equals the integer 6.

The following code illustrates how to force a different numeric type, a byte, for an enumerator:

1.

enum byteEnum : byte

2.

{

3.

    A,

4.

    B

5.

}


Furthermore, any and all of the values of the enumerator can be explicitly set. The default incrementation remains in place, so the following code will set Monday to 1 and Sunday to 7.

1.

public enum DAYS

2.

{

3.

    Monday=1,

4.

    Tuesday,

5.

    Wednesday,

6.

    Thursday,

7.

    Friday,

8.

    Saturday,

9.

    Sunday

10.

}


A useful feature of enumerators is that one can also retrieve the literal as a string from the numeric constant with which it is associated. The following code prints out both the literal and its constant value for the specified enumerator.

1.

using System;

2.

public class EnumTest

3.

{

4.

    public enum DAYS: byte

5.

    {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

6.

    

7.

    public static void Main()

8.

    {

9.

        Array dayArray = Enum.GetValues(typeof(EnumTest.DAYS));

10.

        foreach (DAYS day in dayArray)

11.

            Console.WriteLine("Number {1} of EnumTest.DAYS is {0}", day, day.ToString("d"));

12.

    }

13.

}


(NB: line 11 in the above has been changed to satisfy the final release. It previously ended "..., day, day.toString());")

The output of this code is:

Number 0 of EnumTest.DAYS is Sunday
Number 1 of EnumTest.DAYS is Monday
Number 2 of EnumTest.DAYS is Tuesday
Number 3 of EnumTest.DAYS is Wednesday
Number 4 of EnumTest.DAYS is Thursday
Number 5 of EnumTest.DAYS is Friday
Number 6 of EnumTest.DAYS is Saturday

[Some explanation is required of the string interpolation in the Console.WriteLine method. What happens here is that any number of objects can be passed into the WriteLine method in its params array (see lesson 13). If code {n} is found in the initial string passed to WriteLine, it interpolates into this string the string returned by the 'format' method of the nth extra object passed to it. ]

 

C# Tutorial