c# check enum is contained in options

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.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow