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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With