C # check enum contained in options

I am trying to check if the enumeration option is contained in the available parameters. It’s a little difficult for me to explain this in English. Here is the code:

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


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

I am trying to check if me varliable is contained in the available variable . I know this can be done because it is also used with RegexOptions.

+4
source share
1 answer

The easiest way is to use &:

if ((available & me) != 0)

Here you can use 0, since there is an implicit conversion from constant 0 to any enumeration, which is very convenient.

, Flags :

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

, Flags, List<Fruit> .

+9

Source: https://habr.com/ru/post/1680181/


All Articles