enum contains any of these values?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Consider I have an enum like so:

enum Age {
Baby = 1,
Child = 2,
Teen = 4,
Adult = 8,
Senior = 16
}

Age age = GetAge();
if ((age == Age.Baby) || (age == Age.Child) || .... ) {
// Do something.
}

Is it possible to make the statement above more compact? ie. could I maybe
use enum flags to reduce it.

This obviously will not work:

enum Age {
Baby = 1,
Child = 2,
Teen = 4,
Adult = 8,
Senior = 16,
BelowEighteen = Baby | Child | Teen
}

if (age == Age.BelowEighteen) {
//Do something
}

I am using .net 2.0
Thanks in advance.
 
This obviously will not work:
enum Age {
Baby = 1,
Child = 2,
Teen = 4,
Adult = 8,
Senior = 16,
BelowEighteen = Baby | Child | Teen }
if (age == Age.BelowEighteen) {
//Do something
}

Hi STech, in that case you could try:
if ((age & Age.BelowEighteen) != 0) {
//Do something
}

Personally, I think it is more readable to define a function like:
bool IsBelow18(age) {
return (age == Age.Baby) || (age == Age.Child) || ....;
}
 
Hi STech,

Great question, I took a look at it. This is the code I came up with.

[Flags]
private enum Age
{
Baby = 1,
Child = 2,
Teen = 4,
Adult = 8,
Senior = 16,
BelowEighteen = Baby | Child | Teen
}

private void button1_Click(object sender, System.EventArgs e)
{
Age age = Age.Child;
int found = Age.BelowEighteen.ToString().IndexOf(age.ToString());
if(found > -1)
{
MessageBox.Show( "Below Eighteen");
}


I't probably not the best performant solution but I didn't find any other way.
Hope it's of use to you.
 
You were close. You can use bitwise operators to check more than one
value at once:

if ((age & Age.BelowEighteen) != 0) {
// age is Baby, Child, or Teen
}

Jesse
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

[Flags] Enum -- make it better 1
Question about enum values 10
Alternate enum value 3
QUERY 2
Enum Flags comparison 4
Can I cast to a [Flags] enum? 1
enums bitwise values. 2
Macro for enum values 1

Back
Top