Reputation: 82341
I would like to find a way to check to see if a set of values are contained in my variable.
[Flags]
public enum Combinations
{
Type1CategoryA = 0x01, // 00000001
Type1CategoryB = 0x02, // 00000010
Type1CategoryC = 0x04, // 00000100
Type2CategoryA = 0x08, // 00001000
Type2CategoryB = 0x10, // 00010000
Type2CategoryC = 0x20, // 00100000
Type3 = 0x40 // 01000000
}
bool CheckForCategoryB(byte combinations)
{
// This is where I am making up syntax
if (combinations in [Combinations.Type1CategoryB, Combinations.Type2CategoryB])
return true;
return false;
// End made up syntax
}
I am a transplant to .NET from Delphi. This is fairly easy code to write in Delphi, but I am not sure how to do it in C#.
Upvotes: 5
Views: 259
Reputation: 13699
For an easier way to "check" those value, you might want to check Umbrella on CodePlex. They built some nice and sweet Extension Methods for verifiing bit flags on enums. Yes it's an abstraction but I think we should focus more on the readability than the implementation itself.
Enjoy.
Upvotes: 1
Reputation: 1062780
If you mean "at least one of the flags":
return (combinations
& (byte)( Combinations.Type1CategoryB | Combinations.Type2CategoryB)) != 0;
also - if you declare it as Combinations combinations
(rather than byte
), you can drop the (byte)
bool CheckForCategoryC(Combinations combinations)
{
return (combinations & (Combinations.Type1CategoryB | Combinations.Type2CategoryB) ) != 0;
}
If you mean "exactly one of", I would just use a switch
or if
etc.
Upvotes: 16
Reputation: 22054
I think like this, if I understand the question correctly
if (combinations == Combinations.Type1CategoryB | Combinations.Type2CategoryB)
Upvotes: -2