Iterating enum names and values in C#

Have you ever wanted to create a SELECT element with the names and values of an enum Type? I'll readily admit, in my earlier programming days I used to create the control manually.

Thanks to the C# System.Enum class in .NET and its static helper methods, I can enumerate the Names and Values in an enum Type, increasing maintainability of my application.

System.Enum contains two methods that are of particular interest, these are Enum.GetValues and Enum.GetNames. I'll show you simple examples as to their usage.

In this example, we'll use the following enum declaration:

public enum ProductType { PaperTest, PrintedPaperTest, OnlineTest, Manual, Sample, Book, Other };

In the first example, I'll enumerate the values. Enumerators, by default start with 0. This of course can be overridden in the declaration but is beyond the scope of this article.

// Enumerate the Values
foreach (int value in Enum.GetValues(typeof(ProductType)))
{
    // Do Something with the Values
}

In the next example, I'll enumerate the names of each enum option. This may be useful for generating a SELECT element with options based off of your enum Type.

// Enumerate the Names
foreach (string name in Enum.GetNames(typeof(ProductType)))
{
    // Do Something with the Names
}

Finally, if you want to create Name,Value pairs, you can do something like the following:

// Enumerate the Name, Value pairs
foreach (int value in Enum.GetValues(typeof(ProductType)))
{                
    var producttype = new { value=value, name=Enum.GetName(typeof(ProductType),value) };                

    // Do Something with producttype Name, Value pair
}

For more information on the System.Enum class, refer to the MSDN System.Enum members page, http://msdn.microsoft.com/en-us/library/system.enum_members.aspx

---

As an advanced implementation, the Enum.GetNames method was used to serialize the enum's names as a SELECT element. The technique uses XSLT to transform an object's XML serialization into XHTML.

Below is the code that creates a "product editor" by transforming a product's XML using XSLT.

// Create a new product object
Product product = new Product();

// Generate the paratmeters for the transform
System.Xml.Xsl.XsltArgumentList args = new XsltArgumentList();
args.AddParam(
   "ProductTypes",
   "",  
   Albatross.Xml.Utility.XmlSerialize(
      Enum.GetNames(typeof(ProductType))));

// Create the editor xhtml for the new product
string xhtml = Albatross.Xml.Utility.TransformObject(
  product,
  /templates/product-editor.xsl",
  args)));

Here is a stripped version of the XSL template used to generate the product editor. ProductType names are serialized into an XML ArrayOfString and are accessed by iterating through $ProductTypes/ArrayOfString/string.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:param name="ProductTypes"></xsl:param>


  <xsl:template name="SelectProductType">
    <select name="producttype">
      <xsl:for-each select="$ProductTypes/ArrayOfString/string">
        <option value="{current()}">        
          <xsl:value-of select="current()"/>
        </option>
      </xsl:for-each>
    </select>
  </xsl:template>

</xsl:stylesheet

Recent comments