Count Enum Flag

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • IanWright
    New Member
    • Jan 2008
    • 179

    Count Enum Flag

    Can anyone suggest a simple way to count the number of associated flags as I'm not quite sure how to do so, in a simple way other than repetedly dividing by 2^n...

    Code:
    [Flags]
        public enum Test
        {
            Test1 = 1,
            Test2 = 2,
            Test3 = 4,
            Test4 = 8,
            Test5 = 16,
            Test6 = 32,
            Test7 = 64,
            Test8 = 128
        }
    
        public static int Count(ref Test test)
        {
               // return number of Tests (e.g. 01001001 = 3 )
        }
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Enums implicitly inherit from System.Enum which has a GetNames() which returns all the names of the contants in your enum.

    Comment

    • balabaster
      Recognized Expert Contributor
      • Mar 2007
      • 798

      #3
      Originally posted by r035198x
      Enums implicitly inherit from System.Enum which has a GetNames() which returns all the names of the contants in your enum.
      The easiest way is to use a binary to decimal conversion on your value and then loop through your enum using bit masks:

      Code:
      Dim MyValue = 'Convert binary to decimal here...
      Dim Total = 0
      For Each oVal In System.Enum.GetValues(GetType(MyEnum))
        If oVal && MyValue Then Total += oVal
      Next
      Return Total
      Of course, doing a binary to decimal conversion would render the enum loop superfluous...a nd therefore the enum too...

      Comment

      • IanWright
        New Member
        • Jan 2008
        • 179

        #4
        Originally posted by balabaster
        Count = System.Enums.Ge tValues(GetType (MyEnum)).Lengt h
        Thank you :) Shall give it a whirl. Need to learn to take advantge of the System.Enums namespace I think!

        Comment

        Working...