Is it possible to use an index integer to obtain an enum value? For example, if...
public enum Days { Mon, Tues, Wed, ..., Sun};
...is it somehow possible to write something like...
Days currentDay = Days[index];
Thanks!
No, but you can cast an int to an enum, if the value you are using is defined in the enum, however you do this at your own risk:
Days currentDay = (Days)index;
If you really want to be safe, you can check if it's defined first, but that will involve some boxing, etc and will damper performance.
// checks to see if a const exists with the given value.
if (Enum.IsDefined(typeof(Days), index))
{
currentDay = (Days)index;
}
If you know your enum is a specified, contiguous value range (i.e. Mon = 0 thru Sun = 6) you can compare:
if (index >= (int)Days.Mon && index <= (int)Days.Sun)
{
currentDay = (Days) index;
}
You can also use the array passed back by Enum.GetValues(), but once again this is heavier than the cast:
Day = (Day)Enum.GetValues(typeof(Day))[index];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With