Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104741

Group enum members?

I want to be able to determine if an enum value belongs to a certain group. See the pseudo example:

[Flags]
public enum Animals
{
  Dog = 1,
  Cat = 2,
  WildAnimal = Dog | Cat,
  Fly = 4,
  Bee = 8,
  Insect = Fly | Bee
}

public static bool IsInsect(Animals animals)
{
  return Animals.Insect.Qualifies(animals);
}

public static bool Qualifies(this Animals groupName, Animals value)
{
  //Is there a bitwise operation for it?
}

Upvotes: 4

Views: 3162

Answers (4)

ΩmegaMan
ΩmegaMan

Reputation: 31616

Place a description attribute or a custom attribute off of each individual enum and then get that information from reflection. I provide an example of such usage with enums on my blog entitled:

C# Using Extended Attribute Information on Objects

HTH

Upvotes: 0

Christoffer Lette
Christoffer Lette

Reputation: 14816

Use "and" and check for common bits:

return (groupName & value) > 0;

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

if ((groupName & value) != 0)
    ...

Upvotes: 2

Matej
Matej

Reputation: 7627

Use HasFlag method on enum.

http://msdn.microsoft.com/en-us/library/system.enum.hasflag.aspx

Upvotes: 7

Related Questions