Enum as flags and the switch

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

Guest

Hi,

To exclude users based on a criteria, I have created an enum like so:

[FlagsAttribute]
public enum Exclusions:byte
{
None=0,
HaveEmail=1,
IsAdmin=2
};

I would later like to make decisions based on the enum type setting:

Exclusions exclude = Exclusions.HaveEmail & Exclusions.IsAdmin;

switch(exclude)
{
case Exclusions.None:
//dosomething
break;
case Exclusions.HaveEmail:
//dosomething
break;
case Exclusions.IsAdmin:
//dosomething
break;
case (Exclusions.HaveEmail & Exclusions.IsAdmin): //***ERROR***
//dosomething
break;
}

When I try to handle the case where exclude=3 (HaveEmail & IsAdmin), the
compiler generates an error saying the case is already hadled.

Can someone please illuminate why this is not allowed and tell me if it's
possible to do this without puting numeric constants in my case statement?

Thank you very much,
-Keith
 
Hi Keith,

You need to use bitwise OR rather then AND. with AND it will always give you
0. as long as your flags are only one bit.

The bottom line if you want to combine flags use | operator
 
Keith Harris said:
Hi,

To exclude users based on a criteria, I have created an enum like so:

[FlagsAttribute]
public enum Exclusions:byte
{
None=0,
HaveEmail=1,
IsAdmin=2
};

I would later like to make decisions based on the enum type setting:

Exclusions exclude = Exclusions.HaveEmail & Exclusions.IsAdmin;

switch(exclude)
{
case Exclusions.None:
//dosomething
break;
case Exclusions.HaveEmail:
//dosomething
break;
case Exclusions.IsAdmin:
//dosomething
break;
case (Exclusions.HaveEmail & Exclusions.IsAdmin): //***ERROR***
//dosomething
break;
}

When I try to handle the case where exclude=3 (HaveEmail & IsAdmin), the
compiler generates an error saying the case is already hadled.

Can someone please illuminate why this is not allowed and tell me if it's
possible to do this without puting numeric constants in my case statement?

Thank you very much,
-Keith

Remember you are using and....but you two flags are in binary 01 and
10....if you & them thats 0....you say you want 3...you need to
|...which gives 11 or 3
 
Back
Top