How to retrieve multiple enum values?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • secutos
    New Member
    • Aug 2008
    • 15

    How to retrieve multiple enum values?

    Let's say I have an enumeration like so:

    [Flags]
    public enum Letters
    {
    A = 0,
    B = 1,
    C = 2,
    D = 4,
    E = 8
    }

    And let's say I have a variable like so:

    Letters phrase = Letters.A | Letters.B | Letters.C;

    How would I check to see if "phrase" contains Letter.A, Letter.B, and Letter.C individually?

    e.g. The following code does not work:

    if (phrase == Letters.A)
    {
    // some stuff...
    }
    if (phrase == Letters.B)
    {
    }
    SOLVED

    Solution

    if ((phrase & Letters.A) == Letters.A)
    {
    // true
    }
    else
    {
    // false
    }
    Last edited by secutos; Mar 15 '10, 07:28 PM. Reason: self-solved
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    You have to do a additive check for the bit

    Code:
    if ((phrase & Letters.A) == Letters.A)
    {
       // You have a match
    }
    To make life easy and reduce typing you might want to make a method for checking

    Code:
    private bool IsLettersA(string CheckPhrase)
    {
        if ((CheckPhrase & Leters.A) == Letters.A) return true;
        else return false
    }
    Now you can check like this

    Code:
    if (IsLettersA(Phrase))
    {
       // So something if it is a match
    }

    Comment

    • PRR
      Recognized Expert Contributor
      • Dec 2007
      • 750

      #3
      You can do bitwise OR or AND
      Enumeration Types

      Comment

      Working...