Finding number of elements in enumeration

Problem:

public class myNamespace
{
public enum Day
{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
}

Find the number of days. In other words, find the number of elements in the enumeration.

Solution:

Type enumType = Type.GetType(“myNamespace.Day”);
Type numElementsInEnum = Enum.GetValues(enumType).Length;
int numElementsInEnum = Enum.GetValues(enumType).Length;

Note: Make sure the string which you pass to GetType method is fully qualiified. If the enum is within a namespace, the string should be namespace.enumName and if the enum is in a class which is within a namespace, then the string should be namespace.className.enumName.

MS may include this as a method in System.Enum class in the next version.

Advertisements

20 thoughts on “Finding number of elements in enumeration

  1. Ricardo says:

    In the second line:
    Type numElementsInEnum = Enum.GetValues(enumType).Length;

    what it is returned from Enum.GetValues(enumType).Length is an integer not a Type!

    Thanks for sharing this “trick” with me, it was very helpful
    Ricardo

  2. generally says:

    Thanks for pointing out my mistake, Ricardo. I will fix it right away.

    I am glad you found this post helpful.

  3. Pogo Stick says:

    Is there any better, or easier blog software out there than this? i need something php based that doesnt kill MySQL. Any techie types on this thread that can point me in the right direction?

  4. Alan Balkany says:

    I tried to get the number of HatchStyle types. I had to use GetType (), and the number returned was 3 too high:

    HatchStyle st = new HatchStyle();
    int numElementsInEnum = Enum.GetValues(st.GetType ()).Length;

    It returns 56, but there are only 53 HatchStyle types.

  5. generally says:

    Alan,

    I tried the same thing here and I too get 56. I counted the enum elements and they are 56! I tried on .NET 2.0. Make sure you are programming and reading the document for the same framework version. Here is the list of members for .NET 2.0 and sure thing, there are 56 members.

    http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.hatchstyle(vs.80).aspx

  6. Mirza Efendi says:

    int ElementsInEnum = Enum.GetValues(typeof(myNamespace.Day)).Length;

    so suitable

  7. generally says:

    I agree, Mirza. The only difference I see is you are using typeof and I am using Type.GetType. Pretty much the same thing, isn’t it?

    Thanks for sharing your version.

  8. Brent says:

    At the top I think you meant

    Namespace myNamespace

    instead of ‘public class namespace’

    Thanks.

  9. Anupam says:

    Thanks. this was helpful.

  10. In Vb.net,

    Dim NumberOfElementsInEnum As Integer = [Enum].GetValues(GetType(myNamespace.myEnum)).Length

  11. wolfsinc says:

    In C#,

    int intElements = Enum.GetNames(typeof(myNamespace.Day)).GetUpperBounds(0)+1);

    I use this to dynamically ajust my arrays.

    enum aryFlds { Field01, Field02, Field03, Field04 };

    void SomeFunction()
    {
    string[] array = new string[0];
    Array.Resize(ref array,Enum.GetNames(typeof(myNamespace.Day)).GetUpperBounds(0)+1);
    array[aryFlds.Field01] = “val01”;
    array[aryFlds.Field02] = “val02”;
    array[aryFlds.Field03] = “val03”;
    array[aryFlds.Field04] = “val04”;
    }

    Now if i need to add, removed, or re-order the data I simply modify the enum and then code for any new fields.

  12. wolfsinc says:

    USed wrong array name in the sample code: sorry.

    In C#,

    int intElements = Enum.GetNames(typeof(myNamespace.Day)).GetUpperBounds(0)+1);

    I use this to dynamically ajust my arrays.

    enum aryFlds { Field01, Field02, Field03, Field04 };

    void SomeFunction()
    {
    string[] array = new string[0];
    Array.Resize(ref array,Enum.GetNames(typeof(aryFlds)).GetUpperBounds(0)+1);
    array[aryFlds.Field01] = “val01″;
    array[aryFlds.Field02] = “val02″;
    array[aryFlds.Field03] = “val03″;
    array[aryFlds.Field04] = “val04″;
    }

    Now if i need to add, removed, or re-order the data I simply modify the enum and then code for any new fields.

  13. Pravesh Singh says:

    The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. It is user defined data types. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1
    How use enum keyword in our program

    Example 1:

    enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };

    protected void Page_Load(object sender, EventArgs e)

    {

    int x = (int)Days.Sun;

    Response.Write(x);

    }

    Example 2:

    In this example we store the enum data in dropdown list

    public enum cricketRank

    {

    India = 1,

    SriLanka = 2,

    Pakistan = 3,

    SouthAfrica = 5,

    Englan = 6,

    }

    protected void Page_Load(object sender, EventArgs e)

    {

    if (!IsPostBack)

    {

    //Store the name of country in string type array

    string[] names = Enum.GetNames(typeof(cricketRank));

    //Get the values from countryrank enum

    var values = (cricketRank[])Enum.GetValues(typeof(cricketRank));

    for (int i = 0; i < names.Length; i++)

    DropDownList1.Items.Add(new ListItem(names[i], values.ToString()));

    }

    }

    For more details please check out this link….
    http://mindstick.com/Articles/ade257fc-7058-4f60-a0fe-85c7ca52f004/?Enumeration%20in%20c#
    I hope it might be resolve your problem.

  14. Lighting: Selection of lights can do the secret and should be always done smartly.
    Poor economic situations caused moderation concerning home
    design.

  15. {
    {I have|I’ve} been {surfing|browsing} online more than {three|3|2|4} hours today, yet I never found any interesting article like yours. {It’s|It is} pretty worth
    enough for me. {In my opinion|Personally|In my view}, if all {webmasters|site
    owners|websi

  16. Nice post. I’d been checking continuously this site and We are impressed!

  17. Wow, incredible blog layout! How long have you been blogging for?

    you make blogging look easy. The overall look of your site is wonderful, as
    well as the content!

  18. Hi there! This blog post could not be written much better!

    Reading through this article reminds me of my previous roommate!
    He always kept talking about this. I’ll forward this information to him. Fairly certain he’s going to have a very good read.
    Thank you for sharing!

  19. I read this piece of writing completely on the topic of the resemblance of hottest and preceding
    technologies, it’s remarkable article.

  20. Heⅼlo, ɑll іѕ going sound hеre and ofcourse eѵery one
    is sharing infߋrmation, tɦat’s in fact excellent, кeep up writing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: