Using an enum as an array index in C#

enum array c#
get enum by index c#
c# enum
c# enum property
c# enum string
c# enum attributes
assign string to enum c#
enum class c#

I want to do the same as in this question, that is:

enum DaysOfTheWeek {Sunday=0, Monday, Tuesday...};
string[] message_array = new string[number_of_items_at_enum];

...

Console.Write(custom_array[(int)DaysOfTheWeek.Sunday]);

however, I would rather have something integral to so, rather than write this error prone code. Is there a built in module in C# that does just this?


If the values of your enum items are contigious, the array method works pretty well. However, in any case, you could use Dictionary<DayOfTheWeek, string> (which is less performant, by the way).

C# Enum Array Example, Use Enum as Array Index, Use an array that is indexed with enum values. Cast an enum to an int. C# Enum Array Example, Use Enum as Array Index Use an array that is indexed with enum values. Cast an enum to an int.


You could make a class or struct that could do the work for you


public class Caster
{
    public enum DayOfWeek
    {
        Sunday = 0,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
    }

    public Caster() {}
    public Caster(string[] data) { this.Data = data; }

    public string this[DayOfWeek dow]{
        get { return this.Data[(int)dow]; }
    }

    public string[] Data { get; set; }


    public static implicit operator string[](Caster caster) { return caster.Data; }
    public static implicit operator Caster(string[] data) { return new Caster(data); }

}

class Program
{
    static void Main(string[] args)
    {
        Caster message_array = new string[7];
        Console.Write(message_array[Caster.DayOfWeek.Sunday]);
    }
}

EDIT

For lack of a better place to put this, I am posting a generic version of the Caster class below. Unfortunately, it relies on runtime checks to enforce TKey as an enum.

public enum DayOfWeek
{
    Weekend,
    Sunday = 0,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

public class TypeNotSupportedException : ApplicationException
{
    public TypeNotSupportedException(Type type)
        : base(string.Format("The type \"{0}\" is not supported in this context.", type.Name))
    {
    }
}

public class CannotBeIndexerException : ApplicationException
{
    public CannotBeIndexerException(Type enumUnderlyingType, Type indexerType)
        : base(
            string.Format("The base type of the enum (\"{0}\") cannot be safely cast to \"{1}\".",
                          enumUnderlyingType.Name, indexerType)
            )
    {
    }
}

public class Caster<TKey, TValue>
{
    private readonly Type baseEnumType;

    public Caster()
    {
        baseEnumType = typeof(TKey);
        if (!baseEnumType.IsEnum)
            throw new TypeNotSupportedException(baseEnumType);
    }

    public Caster(TValue[] data)
        : this()
    {
        Data = data;
    }

    public TValue this[TKey key]
    {
        get
        {
            var enumUnderlyingType = Enum.GetUnderlyingType(baseEnumType);
            var intType = typeof(int);
            if (!enumUnderlyingType.IsAssignableFrom(intType))
                throw new CannotBeIndexerException(enumUnderlyingType, intType);
            var index = (int) Enum.Parse(baseEnumType, key.ToString());
            return Data[index];
        }
    }

    public TValue[] Data { get; set; }


    public static implicit operator TValue[](Caster<TKey, TValue> caster)
    {
        return caster.Data;
    }

    public static implicit operator Caster<TKey, TValue>(TValue[] data)
    {
        return new Caster<TKey, TValue>(data);
    }
}

// declaring and using it.
Caster<DayOfWeek, string> messageArray =
    new[]
        {
            "Sunday",
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"
        };
Console.WriteLine(messageArray[DayOfWeek.Sunday]);
Console.WriteLine(messageArray[DayOfWeek.Monday]);
Console.WriteLine(messageArray[DayOfWeek.Tuesday]);
Console.WriteLine(messageArray[DayOfWeek.Wednesday]);
Console.WriteLine(messageArray[DayOfWeek.Thursday]);
Console.WriteLine(messageArray[DayOfWeek.Friday]);
Console.WriteLine(messageArray[DayOfWeek.Saturday]);

Using enums to index arrays : csharp, a lot in a lot of other people's projects is declaring an enum, and using it to index arrays, like: Make a platform game with windows form and c# mini project​. C# Enum Array Example, Use Enum as Array Index Use an array that is indexed with enum values. Cast an enum to an int.


Here you go:

string[] message_array = Enum.GetNames(typeof(DaysOfTheWeek));

If you really need the length, then just take the .Length on the result :) You can get values with:

string[] message_array = Enum.GetValues(typeof(DaysOfTheWeek));

https://social.msdn.microsoft.com/Forums/en-US/129, Okay gang, This should be simple but apparently it's not I want to use the System.DayOfWeek enum to create and access an array of objects  It is perfectly normal to use an enum for indexing into an array. You don’t have to specify each enum value, they will increment automatically by 1. Letting the compiler pick the values reduces the possibility of mistyping and creating a bug, but it deprives you of seeing the values, which might be useful in debugging.


Since C# 7.3 it has been possible to use System.Enum as a constraint on type parameters. So the nasty hacks in the some of the other answers are no longer required.

Here's a very simple ArrayByEum class that does exactly what the question asked.

Note that it will waste space if the enum values are non-contiguous, and won't cope with enum values that are too large for an int. I did say this example was very simple.

/// <summary>An array indexed by an Enum</summary>
/// <typeparam name="T">Type stored in array</typeparam>
/// <typeparam name="U">Indexer Enum type</typeparam>
public class ArrayByEnum<T,U> : IEnumerable where U : Enum // requires C# 7.3 or later
{
  private readonly T[] _array;
  private readonly int _lower;

  public ArrayByEnum()
  {
    _lower = Convert.ToInt32(Enum.GetValues(typeof(U)).Cast<U>().Min());
    int upper = Convert.ToInt32(Enum.GetValues(typeof(U)).Cast<U>().Max());
    _array = new T[1 + upper - _lower];
  }

  public T this[U key]
  {
    get { return _array[Convert.ToInt32(key) - _lower]; }
    set { _array[Convert.ToInt32(key) - _lower] = value; }
  }

  public IEnumerator GetEnumerator()
  {
    return Enum.GetValues(typeof(U)).Cast<U>().Select(i => this[i]).GetEnumerator();
  }
}

Usage:

ArrayByEnum<string,MyEnum> myArray = new ArrayByEnum<string,MyEnum>();
myArray[MyEnum.First] = "Hello";

myArray[YourEnum.Other] = "World"; // compiler error

Enum as array index? - C# / C Sharp, An array could be declared with an enum type as its index: int[Color] colorValueMap = new [Color] { 1, 2, 3 }; the compiler would return an error if the above "new [Colors] { 1, 2, 3 }" didn't have the same number of elements as enum Color. enum array index in c#. totals.red += currentPixel.red; totals.green += currentPixel.green; totals.blue += currentPixel.blue; I'd like to reduce this copy-pasting and vulnerability to copy-paste errors. I could use arrays of size 3 around the place, but accessing those by number reduces readability.


Compact form of enum used as index and assigning whatever type to a Dictionary and strongly typed. In this case float values are returned but values could be complex Class instances having properties and methods and more:

enum opacityLevel { Min, Default, Max }
private static readonly Dictionary<opacityLevel, float> _oLevels = new Dictionary<opacityLevel, float>
{
    { opacityLevel.Max, 40.0 },
    { opacityLevel.Default, 50.0 },
    { opacityLevel.Min, 100.0 }
};

//Access float value like this
var x = _oLevels[opacitylevel.Default];

Discussion: C# Support for fixed sized arrays with enum indexes , Use an enumeration to index an array : enum « Data Type « C# / CSharp Tutorial​. It is perfectly normal to use an enum for indexing into an array. You don't have to specify each enum value, they will increment automatically by 1. Letting the compiler pick the values reduces the possibility of mistyping and creating a bug, but it deprives you of seeing the values, which might be useful in debugging.


Use an enumeration to index an array : enum « Data Type « C# , C# program that uses enum indexes using System; /// <summary> /// Enum values used to index array. /// </summary> enum MessageType { Startup, Shutdown,  In C#, enum is a value type data type. The enum is used to declare a list of named integer constants. It can be defined using the enum keyword directly inside a namespace, class, or structure. The enum is used to give a name to each constant so that the constant integer can be referred using its name.


C# Enum Array Example, ///This is used to get Enum values as array. private static void GetEnumValues(); {​  How to get the Enum Index value in C#. In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.


How To Play With Enum in C#, To declare an array, define the variable type with square brackets: string[] cars; Note: Array indexes start with 0: [0] is the first element. [1] is the second  If you have enum of days of week like: public enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } and arrays like: String days[]=new String[7] The indexing in the array can only be done by int.So you can use enum as the indexes as: days[Days.SUNDAY.ordinal()]="sunday"; System.out.println(days[Days.SUNDAY.ordinal()]);