How to Get Enum Values with Reflection in C#

This came up when I was writing a UIProperty for SmartCodeGenerator,
The combo box should display all the available enum options in a DropDownList for the enduser to choose from them.

So if someone defines a enum like this:
public enum MyEnum
{
  ten = 10,
  twenty = 20 ,
  thirty = 30
}

and a class using the enum as one of its property, ie.

public class TheProperties
{
  public TheProperties( )
  {
    //Please Assign Default Values here
    this.myVar = MyEnum.twenty;
  }

  private MyEnum testEnumProp; 

  public MyEnum TestEnumProp
  {
    get { return testEnumProp; }
    set { testEnumProp = value; }
  }

}

For this declaration above my Objective is to comeup with a ASP.Net DropDownList  with the endresult in html like this:

  ten   twenty   thirty

Ok here is the code to achieve this:

object profile = new TheProperties();
foreach (PropertyInfo propertyInfo in profile.GetType().GetProperties())
{
  if ((info.PropertyType.IsEnum) && (info.PropertyType.IsPublic))
  {
    foreach (FieldInfo fInfo in this.propertyInfo.PropertyType.GetFields(BindingFlags.Public | BindingFlags.Static))
    {
      //ListItem item = new ListItem(fInfo.Name, ((int)fInfo.GetValue(this.propertyInfo)).ToString());//.Net1.1
      ListItem item = new ListItem(fInfo.Name, fInfo.GetRawConstantValue().ToString());
      ddProperty.Items.Add(item);
    }
  }
}

in .Net2.0 we have this nice little function GetRawConstantValue() which returns the value associated with enum (in this example 10, 20, 30)
in .Net1.1 we have to do it in old fashioned way with the GetValue(...) method.

This article is part of the GWB Archives. Original Author: Shahed Khan

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.