Link to home
Start Free TrialLog in
Avatar of davidlars99
davidlars99Flag for United States of America

asked on

Flagged enum equation logic

HI,

Suppose I have:

[Flags]
enum Fruits
{
     None = 0,
     Apple = 1,
     Orange = 2,
     Peach = 4,
     Banana = 8
}

and then I initialize a avriable:

Fruits fruits = Fruits.Apple | Fruits.Orange | Fruits.Banana;

how do I then find out if "fruits" variable is equal to "Banana"

It would be really great if I could do something like this:

if (fruits == Fruits.Banana)
{
     // do something
}

but unfortunately, it's not that convenient.
ASKER CERTIFIED SOLUTION
Avatar of Chumad
Chumad

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, not a C# coder, and not sure of the syntax, but with bitwise stuff you want to OR stuff together, and use AND to figure out if it is part of...

if (Convert.ToBoolean(fruits & Fruits.Banana))
{
     // do something
}
Chumad's post will work if you change it to:
if ((fruits & Fruits.Banana)  == Fruits.Banana) {
   //do something
}

Jim
lol...three of the same but different answers in three mins!  must be a record.
Avatar of davidlars99

ASKER

this return match too even though Fruits.Peach is not part of the group:

Fruits fruits = Fruits.Apple | Fruits.Orange | Fruits.Banana;

if ((fruits & Fruits.Peach)  == Fruits.Peach)
{
   //do something
}

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If this works then you are not suppose to see the message box right?
I do not see this behavior. Running this code:
public enum TestEnum
{
   None = 0,
   Apple = 1,
   Bananna = 2,
   Orange = 4,
   Pineapple = 8
};

string hello = "We have Banannas";

TestEnum te1 = TestEnum.Apple | TestEnum.Bananna;
if ((te1 & TestEnum.Orange) == TestEnum.Orange)
{
   hello = "Now we have a Oranges?";
}

When completed, we still have banannas, and not oranges.

Jim
So, are you getting into the IF block or not?
You're right, it works... :)
I did not alter the string.

Jim
That's right, you didn't.

Thanks for your help!!!
One last thing:

How do I determine if a flagged enum has more than one group?
Something like this will work, cannot think of a better way offhand.

public bool IsSalad( Fruits selection )
{
   int count = 0;
   if ((selection & Fruits.Apple) == Fruits.Apple)
      count++;
   if ((selection & Fruits.Banana) == Fruits.Banana)
      count++;
   etc.
   return (count > 1);
}
what about this?

if ((int)selection) > 1)
{
   // multiple selection
}