views:

192

answers:

1

What's the best way in code to compare enum values? For example, if I have the following enum type:

public enum Level : short {
    Low,   
    FairlyLow,
    QuiteLow,
    NotReallyLow,
    GettingHigh,
    PrettyHigh,
    High,
    VeryHigh,
}

And I want to be able to write statements such as:

from v in values select v where v > Level.QuiteLow
+3  A: 

You need to cast the enum value to its numeric value, because enum values aren't comparable :

from v in values where (short)v > (short)Level.QuiteLow select v

EDIT: actually this is not true : enum values are comparable, so this code works fine :

from v in values where v > Level.QuiteLow select v
Thomas Levesque
Thanks for that, I was mostly checking that there wasn't a better (or other) way of doing this. I also padded out the enum values a bit:public enum Level : short { Low = 1, FairlyLow = 5, QuiteLow = 10, NotReallyLow = 15, GettingHigh = 20, PrettyHigh = 30, High = 40, VeryHigh = 60,}
Qwerty
I can't imagine any better way, this one seems optimal to me ;)
Thomas Levesque
Please note though that this depends on the ordering of the enum values, IE if QuiteLow and NotReallyLow were swapped then it would improperly compare values.
RCIX
which is, in-part, why I padded out the values... so that new items can be inserted without disrupting the order or the numerical values.
Qwerty