-2

I would like to know more about enums in C#. is it best practice to use enum for creating custom variables? or we can use some another better approach for below example. How we can access it and store enum values to an array of integer using foreach or for loop or any other method.

enum timeSlots
        {
            AM9h = 0,
            AM10h = 1,
            AM11h = 2,
            AM12h = 3,
            PM1h = 4,
            PM2h = 5,
            PM3h = 6,
            PM4h = 7,
            PM5h = 8,
            PM6h = 9,
        }

how can I store timeslots enum's value to an int array?

Nexo
  • 2,125
  • 2
  • 10
  • 20
  • 1
    You need the end result of timeSlots integer array to be something like this: int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}? – Wael Alshabani Sep 30 '21 at 21:58
  • Have you tried anything? What issues have you run into? Do you know how to [convert an enum value to an int](https://stackoverflow.com/questions/943398/get-int-value-from-enum-in-c-sharp)? – Joe Sewell Sep 30 '21 at 21:58
  • I am confused so much now. – Nexo Sep 30 '21 at 22:05
  • @WaelAlshabani Yes I am trying to do that. as I need that int array later in my program. – Nexo Sep 30 '21 at 22:06
  • @Nikkkshit please [edit] the question with information on what you tried and where you stuck in addition to what you actually want to achieve. To me it looks like you are not able to convert enum values to int and back - so I picked couple duplicates that show that... I apologize as it is quite offensive to assume you don't know that (or even worse would be to assume you can't add elements to a list/create array or get list of enum values). Again editing the question would save everyone from providing such offensive comments and answers. – Alexei Levenkov Sep 30 '21 at 22:35
  • Why do you want to store the int values? Just store the timeslots. [You can store things other than ints in an array](https://wiki.c2.com/?PrimitiveObsession). – Dour High Arch Sep 30 '21 at 23:18

2 Answers2

1

Well... you can't really. C# is strongly-typed, after all, so any integer array is always going to store integers.

Now what you can do is cast an enum to an int when you want to store it in one of the array elements, and cast it back to the enum type when you need it again. Or you can declare an array of your enum type.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Hello, Thanks for your answer can you share the code if possible that would be great help for me. – Nexo Sep 30 '21 at 22:06
0

Looks like what you're looking for is Enum.GetValues. Here's an example:

var enums = Enum.GetValues(typeof(timeSlots));
var count = enums.Length;
var array = new int[count];

for(var i = 0; i < count; i++)
    array[i] = enums[i];          

Not on a computer, so can't test it out right now. Hope it gives you some direction.

nebula
  • 73
  • 4