Indexing arrays with enums in C# Indexing arrays with enums in C# arrays arrays

Indexing arrays with enums in C#


I suspect you may be able to make it a bit faster by compiling a delegate to do the conversion for you, such that it doesn't require boxing and unboxing. An expression tree may well be the simplest way of doing that if you're using .NET 3.5. (You'd use that in your EnumArray example.)

Personally I'd be very tempted to use your const int solution. It's not like .NET provides enum value validation anyway by default - i.e. your callers could always cast int.MaxValue to your enum type, and you'd get an ArrayIndexException (or whatever). So, given the relative lack of protection / type safety you're already getting, the constant value answer is appealing.

Hopefully Marc Gravell will be along in a minute to flesh out the compiled conversion delegate idea though...


If your EnumArray wasn't generic, but instead explicitly took a StatType indexer - then you'd be fine. If that's not desirable, then I'd probably use the const approach myself. However, a quick test with passing in a Func<T, E> shows no appreciable difference vs direct access.

 public class EnumArray<T, E> where E:struct {    private T[] _array;    private Func<E, int> _convert;    public EnumArray(int size, Func<E, int> convert) {        this._array = new T[size];        this._convert = convert;    }    public T this[E index] {        get { return this._array[this._convert(index)]; }        set { this._array[this._convert(index)] = value; }    } }


If you have a lot of fixed-size collections, then it would probably be easier to wrap up your properties in an object than a float[]:

public class Stats{    public float Foo = 1.23F;    public float Bar = 3.14159F;}

Passing an object around will give you the type safety, concise code, and constant-time access that you want.

And if you really need to use an array, its easy enough to add a ToArray() method which maps the properties of your object to a float[].