I realize that I can select an element from an array from an enum by casting it as an int, but since I need to do that numerous times in my code, I was wondering if there is a way to set up a property or something like that to reduce code duplication. How would I be able to do something like this?
Asked
Active
Viewed 963 times
1 Answers
0
Casting an enum
to an int
extremely efficient. In fact, in most cases, the compiler does most of the work for you already. For example, using a constant like this arr[(int)MyEnum.Value]
will be automatically compiled into an int literal like arr[7]
.
So there's really no need to try to speed this up.
However, if your enum
values do not strictly range from 0 — n, (where n < array.length
), then suggest using a Dictionary
instead.

p.s.w.g
- 146,324
- 30
- 291
- 331
-
1My point wasn't to make it faster. I want to reduce code duplication of casting. Also, I could do a check once for invalid enums if it was separate in a property. – DeadEli Jan 31 '14 at 22:39