Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an enum as an array index in C#

Tags:

c#

enums

indexing

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?

like image 202
Nefzen Avatar asked Jun 11 '09 15:06

Nefzen


1 Answers

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).

like image 162
mmx Avatar answered Sep 20 '22 10:09

mmx