Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum flag attribute C#

i'be looked some same topics but havn't find what i'm looking for I should use flag enum flag atribute and check if my data is in one of the collections of this enum For example, enum:

[Flags]
private enum MyEnum {
Apple,
Orange,
Tomato,
Potato
Melon,
Watermelon,

Fruit = Apple | Orange,
Vegetable = Tomato | Potato,
Berry = Melon | Watermelon,
}

In the method i should check a input data. How can i do it?

private void Checking(string data){
if(MyEnum.Fruit contains data) MessageBox.Show("Fruit");
if(MyEnum.Vegetable contains data) MessageBox.Show("Vegetables");
if(MyEnum.Berry contains data) MessageBox.Show("Berry");
}

What should be instead of "contains data"?

UPDATE

private void ZZZ(){
Cheching("Apple");
}
like image 470
Bashnia007 Avatar asked Aug 19 '13 09:08

Bashnia007


1 Answers

First of, you need to manually number your values with the powers-of-2 sequence :

[Flags]
private enum MyEnum 
{
  None = 0,   // often useful
  Apple = 1,
  Orange = 2,
  Tomato = 4,
  Potato = 8,
  Melon =  16,
  Watermelon = 32,

  Fruit = Apple | Orange,
  Vegetable = Tomato | Potato,
  Berry = Melon | Watermelon,
}

The [Flags] attribute is not strictly necessary, it only controls the ToString() behaviour.

And to check whether a string matches your value you'll have to make it an enum first:

private void Checking(string data)
{      
    MyEnum v = (MyEnum) Enum.Parse(typeof(MyEnum), data);

    if((MyEnum.Fruit & v) != 0) MessageBox.Show("It's a Fruit"); 
    ...
}

But do note that interchanging between Enum and string like this with Parse() is limited.

like image 83
Henk Holterman Avatar answered Oct 07 '22 03:10

Henk Holterman