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
 
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
 
Back
Top