Enum
, array indexesAn enum
array has many uses. It can be accessed with enum
values. This example shows how to index an array of values with enum
keys.
This technique is ideal for some kinds of data such as numeric data. It provides another way to keep track of values or statistics.
Enums are value types (usually Int32
). Like any integer value, you can access an array with their values. Enum
values are ordered starting with zero, based on their textual order.
MessageType
enum
, which is a series of int
values you can access with strongly-typed named constants.class
contains an array. Each MessageType
has an element in the array.MessageType.Startup
is 0. MessageType.Error
is 5.enumerated
values. The for
-loop here goes through each enum
except the last one.using System; /// <summary> /// Enum values used to index array. /// </summary> enum MessageType { Startup, Shutdown, Reload, Refresh, Sleep, Error, Max } /// <summary> /// Contains array of elements indexed by enums. /// </summary> static class Message { /// <summary> /// Contains one element per enum. /// </summary> public static int[] _array = new int[(int)MessageType.Max]; } class Program { static void Main() { // Assign an element using enum index. Message._array[(int)MessageType.Startup] = 3; // Assign an element. Message._array[(int)MessageType.Error] = -100; // Increment an element using enum index. Message._array[(int)MessageType.Refresh]++; // Decrement an element using enum index. Message._array[(int)MessageType.Refresh]--; // Preincrement and assign an element. int value = ++Message._array[(int)MessageType.Shutdown]; // Loop through enums. for (MessageType type = MessageType.Startup; type < MessageType.Max; type++) { Console.Write(type); Console.Write(' '); Console.WriteLine(Message._array[(int)type]); } } }Startup 3 Shutdown 1 Reload 0 Refresh 0 Sleep 0 Error -100
This code shows how to use a global variable array. When using global variables, consider using accessor routines, which provide a level of abstraction.
Our code is vulnerable to exceptions during runtime. Access routines can mitigate this. But for variables that must be statics, it is still best to use separate variables.
Array elements can be accessed with enums. We next discussed some problems with this code and some of its benefits. Access routines can be used to make programs more reliable.