Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enum Indexing Question

Tags:

c#

enums

indexing

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!

like image 793
john Avatar asked Jan 18 '26 14:01

john


1 Answers

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];
like image 162
James Michael Hare Avatar answered Jan 21 '26 07:01

James Michael Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!