say I have the following declarations:
public enum Complexity { Low = 0, Normal = 1, Medium = 2, High = 3 } public enum Priority { Normal = 1, Medium = 2, High = 3, Urgent = 4 }
and I want to code it so that I could get the enum value (not the index, like I earlier mentioned):
//should store the value of the Complexity enum member Normal, which is 1 int complexityValueToStore = EnumHelper.GetEnumMemberValue(Complexity.Normal); //should store the value 4 int priorityValueToStore = EnumHelper.GetEnumMemberValue(Priority.Urgent);
How should this reusable function look like?
tia! -ren
Revised answer (after question clarification)
No, there’s nothing cleaner than a cast. It’s more informative than a method call, cheaper, shorter etc. It’s about as low impact as you could possibly hope for.
Note that if you wanted to write a generic method to do the conversion, you’d have to specify what to convert it to as well: the enum could be based on
byteorlongfor example. By putting in the cast, you explicitly say what you want to convert it to, and it just does it.Original answer
What do you mean by ‘index’ exactly? Do you mean the numeric value? Just cast to
int. If you mean ‘position within enum’ you’d have to make sure the values are in numeric order (as that’s whatEnum.GetValuesgives – not the declaration order), and then do: