calculating number of elements in an enumerated type

  • Thread starter Thread starter Claire
  • Start date Start date
C

Claire

Is there an easy way to return the number of elements in an enumerated type
please
thanks
Claire
 
Hi Claire,

Enum.GetNames(typeof(YourEnum)); // for names of enum
Enum.GetValues(typeof(YourEnum)); // for values of enum

Cheers

Marcin
 
Claire said:
Is there an easy way to return the number of elements in an enumerated type

Given the enum,

enum BirthdayInvitee
{
Linda = 1,
Dexter = 2,
Jennifer = 3,
Renee = 4,
Joe = 5
}

Then I can get the length of the number of Enum names for this type like this,

int invitationsReqd = Enum.GetNames( typeof( BirthdayInvitee)).Length;


Derek Harmon
 
You could try Enum.GetValues(typeof( [name of enumeration here] )).Length
 
Is there an easy way to return the number of elements in an enumerated type
please
thanks
Claire
There are several useful replies involving Enum.GetValues.

However, if your enumeration doesn't set explicit values but just
lets them default to 0, 1, 2, ... then I sometime just include a Last
member, e.g.,

enum cardSuits {clubs, spades, diamonds, hearts, Last}

then the number of "real" values in the enumeration reduces
to cardSuits.Last which can be cast to whatever type of
counting variable you wish, int, long, byte...

Oz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top