You can count the number of constants defined in a C# enumeration with the static Enum.GetNames method. This returns an Array containing the names of the constants defined in the enumeration. You can then check the Array’s Length property.

For example, to get the number of constants defined in the ContentAlignment enumeration:

int count = Enum.GetValues( typeof( ContentAlignment ) ).Length;

Note that you can also use the Enum.GetValues method to count the items in an enumeration, however GetNames is 10X faster than GetValues! Perhaps this performance difference is the result of boxing and unboxing of integer values in the Array for Enum.GetValues? Comment if you know why.

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot