5

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#.

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you are going to do this, it would also be a good idea to declare public enum Combinations : byte.
Heh, +1 from me for being quick enough to both get the answer up and get 10 upvotes before i even posted mine :)
1

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.

Comments

-2

I think like this, if I understand the question correctly

if (combinations == Combinations.Type1CategoryB | Combinations.Type2CategoryB)

1 Comment

That will not work if combination is anything else besides the two possibilities. assume combinations = Type1CategoryB | Type2CategoryB | Type2CategoryC. Then your check fails, which is not what's wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.