Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# check enum is contained in options [duplicate]

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.

like image 725
djsony90 Avatar asked Jun 27 '17 08:06

djsony90


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

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.

like image 190
Jon Skeet Avatar answered Sep 25 '22 06:09

Jon Skeet