Number of members in an Enum

  • Thread starter Thread starter Jay
  • Start date Start date
J

Jay

I have a few enums, a shortened example of one is:

enum ParamTest {Err, Start, Block, Hold}

Is there a programmatic way to find the number of "members" (probably the wrong C# term) of the
Enum - this is 4 for the example given.

One not very good way that I currently use is to add a dummy "LENGTH" member on the end:

enum ParamTest {Err, Start, Block, Hold, LENGTH}

and to always remember not to assign values to the members, and to keep LENGTH at the end of the
enum if any extra members are added. That way, I can use ParamTest.LENGTH to find the number of
members (excluding the dummy one). This is messy. Is there a better way?
 
Hi

Look at the "Enum" method. One such way of doing what you want is this:

string[] strEnumArry = Enum.GetNames(myEnum); //returns your enum into a
string array

int enumLen = strEnumArry.GetLength(); //gets you the length of that
array
 
Thank Daniel, that's a good idea. I need the string array anyway.

I have another question on enums, but it's not really related, so I think I'll start a new post.



Hi

Look at the "Enum" method. One such way of doing what you want is this:

string[] strEnumArry = Enum.GetNames(myEnum); //returns your enum into a
string array

int enumLen = strEnumArry.GetLength(); //gets you the length of that
array
 
Back
Top