Suppose you have
public enum Week { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
How can one get int
representing that Sunday is 0, Wednesday is 3 etc?
Numeric Enum Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
To convert a string to ENUM or int to ENUM constant we need to use Enum. Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.
Week week = Week.SUNDAY; int i = week.ordinal();
Be careful though, that this value will change if you alter the order of enum constants in the declaration. One way of getting around this is to self-assign an int value to all your enum constants like this:
public enum Week { SUNDAY(0), MONDAY(1) private static final Map<Integer,Week> lookup = new HashMap<Integer,Week>(); static { for(Week w : EnumSet.allOf(Week.class)) lookup.put(w.getCode(), w); } private int code; private Week(int code) { this.code = code; } public int getCode() { return code; } public static Week get(int code) { return lookup.get(code); } }
You can call:
MONDAY.ordinal()
but personally I would add an attribute to the enum
to store the value, initialize it in the enum
constructor and add a function to get the value. This is better because the value of MONDAY.ordinal
can change if the enum
constants are moved around.
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