# VBForums CodeBank > CodeBank - C# >  [.NET 2.0+] Displaying Friendly Names for Enumerations

## jmcilhinney

VB version here.

I've seen information on this technique in several places, possibly even on this forum.  I've extended what I've read by creating a couple of classes that make displaying friendly names easier.

First, a bit of background.  Enumerations, created in C# with the 'enum' key word, are lists of text values that each correspond to a number.  They are used to provide a limited list of possible values.  We use them in many situations, for instance the DialogResult values that are returned by MessageBox.Show are members of the DialogResult enumeration.  The idea is that the text labels are descriptive and make life easier for the developer, while the system uses the underlying numeric values for speed and efficiency.  Enumerations are better than either String or Integer when you want to limit the possible choices a variable can take.

I say that the text labels are friendly to the developer, but what about the user?  The text labels used for enumerated constants must obey the same rules as other identifiers.  That means that they must start with a letter or an underscore and can only contain letters, numbers and underscores.  They cannot contain spaces or punctuation.  That makes them a little less friendly to display to the user in the UI.  It would be nice if we could associate a standard String with each value and display those to the user.  Well, we can do that, using the DescriptionAttribute class:
CSharp Code:
using System.ComponentModel; public enum TestEnum{    [Description("This is the first value")]    FirstValue,    [Description("Hello from the second value")]    SecondValue,    [Description("Third value here")]    ThirdValue}
Note the spaces in the descriptions that are not allowed in the value names themselves.  Now, the question is, how do we actually get those descriptions in code?  The answer is to use reflection.  In other places I've seen this done with a method at the form level or the like.  I've been a good little OOPer and created a couple of classes to do the job.  The following EnumDescriptor class encapsulates the reflection code, providing access to an enumerated value and its description via properties:
CSharp Code:
using System.ComponentModel;using System.Reflection; /// <summary>/// Contains an enumerated constant value and a friendly description of that value, if one exists./// </summary>/// <typeparam name="T">/// The enumerated type of the value./// </typeparam>public class EnumDescriptor<T>{    /// <summary>    /// The friendly description of the value.    /// </summary>    private string _description;    /// <summary>    /// The enumerated constant value.    /// </summary>    private T _value;     /// <summary>    /// Gets the friendly description of the value.    /// </summary>    /// <value>    /// A <b>String</b> containing the value's Description attribute value if one exists; otherwise, the value name.    /// </value>    public string Description    {        get        {            return this._description;        }        set        {            this._description = value;        }    }     /// <summary>    /// Gets the enumerated constant value.    /// </summary>    /// <value>    /// An enumerated constant of the <b>EnumDescriptor's</b> generic parameter type.    /// </value>    public T Value    {        get        {            return this._value;        }        set        {            this._value = value;        }    }     /// <summary>    /// Creates a new instance of the <b>EnumDescriptor</b> class.    /// </summary>    /// <param name="value">    /// The value to provide a description for.    /// </param>    public EnumDescriptor(T value)    {        this._value = value;         // Get the Description attribute.        FieldInfo field = value.GetType().GetField(value.ToString());        DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute),                                                                                              false);         // Use the Description attribte if one exists, otherwise use the value itself as the description.        this._description = attributes.Length == 0 ? value.ToString()                                                   : attributes[0].Description;    }     /// <summary>    /// Overridden.  Creates a string representation of the object.    /// </summary>    /// <returns>    /// The friendly description of the value.    /// </returns>    public override string ToString()    {        return this._description;    }}
I've also created a class to automatically create an EnumDescriptor for each member of an enumeration and store them as a collection:
CSharp Code:
using System; /// <summary>/// A collection of EnumDescriptors for an enumerated type./// </summary>/// <typeparam name="T">/// The type of the enumeration for which the EnumDescriptors are created./// </typeparam>public class EnumDescriptorCollection<T> : System.Collections.ObjectModel.Collection<EnumDescriptor<T>>{    /// <summary>    /// Creates a new instance of the <b>EnumDescriptorCollection</b> class.    /// </summary>    public EnumDescriptorCollection()    {        // Populate the collection with an EnumDescriptor for each enumerated value.        foreach (T value in Enum.GetValues(typeof(T)))        {            this.Items.Add(new EnumDescriptor<T>(value));        }    }}
An example of how you might use these classes is:
CSharp Code:
private void Form1_Load(object sender, EventArgs e){    this.comboBox1.DisplayMember = "Description";    this.comboBox1.ValueMember = "Value";    this.comboBox1.DataSource = new EnumDescriptorCollection<TestEnum>();} private void comboBox1_SelectedIndexChanged(object sender, EventArgs e){    MessageBox.Show(this.comboBox1.SelectedValue.ToString(), this.comboBox1.Text);}
So, there's no need for you to mess around each time you want to do this once you have these classes.  It's one line to create a collection containing the enumerated values and their descriptions, which you can bind or use however you like.

I've attached code files for the EnumDescriptor and EnumDescriptorCollection classes.

----------


## jmcilhinney

Here's a more succinct version of the EnumDescriptor class for more recent versions of C#:

csharp Code:
using System.ComponentModel;using System.Linq; /// <summary>/// Contains an enumerated constant value and a friendly description of that value, if one exists./// </summary>/// <typeparam name="T">/// The enumerated type of the value./// </typeparam>public class EnumDescriptor<T>{    /// <summary>    /// Gets the friendly description of the value.    /// </summary>    /// <value>    /// A <b>String</b> containing the value's Description attribute value if one exists; otherwise, the value name.    /// </value>    public string Description { get; set; }     /// <summary>    /// Gets the enumerated constant value.    /// </summary>    /// <value>    /// An enumerated constant of the <b>EnumDescriptor's</b> generic parameter type.    /// </value>    public T Value { get; set; }     /// <summary>    /// Creates a new instance of the <b>EnumDescriptor</b> class.    /// </summary>    /// <param name="value">    /// The value to provide a description for.    /// </param>    public EnumDescriptor(T value)    {        this.Value = value;         // Get the Description attribute.        var field = value.GetType().GetField(value.ToString());        var descriptionAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false)                                        .Cast<DescriptionAttribute>()                                        .FirstOrDefault();         // Use the Description attribte if one exists, otherwise use the value itself as the description.        Description = descriptionAttribute?.Description ?? value.ToString();    }     /// <summary>    /// Overridden.  Creates a string representation of the object.    /// </summary>    /// <returns>    /// The friendly description of the value.    /// </returns>    public override string ToString()    {        return Description;    }}

----------

