7

I'm trying to check if an enum option is contained in the available options. Its a little bit difficult for me to explain it in english. Here's the code:

public enum Fruits
{
    Apple,
    Orange,
    Grape,
    Ananas,
    Banana
}


var available = Fruits.Apple | Fruits.Orange | Fruits.Banana;
var me = Fruits.Orange;

I'm trying to check if the me varliable is contained in the available variable. I know it can be done because it's used with the RegexOptions too.

djsony90
  • 952
  • 1
  • 8
  • 19

1 Answers1

9

The simplest way is to use &:

if ((available & me) != 0)

You can use 0 here as there's an implicit conversion from the constant 0 to any enum, which is very handy.

Note that your enum should be defined using the Flags attribute and appropriate bit-oriented values though:

[Flags]
public enum Fruits
{
    Apple = 1 << 0,
    Orange = 1 << 1,
    Grape = 1 << 2,
    Ananas = 1 << 3,
    Banana = 1 << 4
}

If you don't want to make it a Flags enum, you should use a List<Fruit> or similar to store available options.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • 1
    Have a look at the [FlagsAttribute](https://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx) for your enumeration. This also enables you to use the [HasFlag method](https://msdn.microsoft.com/en-us/library/system.enum.hasflag.aspx). – rickvdbosch Jun 27 '17 at 08:41
  • thanks a lot, this is just what i needed – djsony90 Jun 27 '17 at 09:01