C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: This example shows how to index an array of values with enum keys. It shows an array with enhanced syntax.
MessageType: We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.
Message: This class contains an array. The array is initialized to contain the number of elements equal to the count constants in the MessageType enum.
ArrayAnd: The enumeration values are treated as integers by using explicit casts. MessageType.Startup is 0. MessageType.Error is 5.
Finally: The example shows how to loop through enumerated values. The for-loop here goes through each enum except the last one.
ForC# program that uses enum indexes
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]);
}
}
}
Output
Startup 3
Shutdown 1
Reload 0
Refresh 0
Sleep 0
Error -100
Info: The example does not show any access routines, but you could implement some on Message.
Tip: It would be best to even remove the public modifier from the array. You can find tips on access routines in Code Complete.
Public, privateTip: Because the array lookup must occur before getting the value, the code here is slightly slower in many cases as well.
But: On the other hand, it forces the variable to stored together, which will provide better locality of reference.