I had the desire to create an enumeration in C# the other day and I wanted to be able to attach a description to each item in the enumeration. I did the searching on the internets and put together examples from several sources that I found. Here is an example that ties it all together in a Windows Console applicaton in C#.
using System;
using System.Reflection;
namespace DescriptiveEnums
{
///
/// Create the custom Attribute named Description
///
public class DescriptionAttribute : Attribute
{
public String StringValue { get; protected set; }
public DescriptionAttribute(String value)
{
this.StringValue = value;
}
}
///
/// Attach a method ToDescriptionString to our enumeration that enables us
/// to get the value of our custom Description attribute.
///
public static class MyCustomEnumerationExtensions
{
public static String ToDescriptionString(this MyCustomEnumeration value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the Description attributes
DescriptionAttribute[] attributes =
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
// Return the first if there was a match
return attributes.Length > 0 ? attributes[0].StringValue : String.Empty;
}
}
///
/// Enumeration for demonstration
///
public enum MyCustomEnumeration
{
[Description("Item One Description")]
ITEM_ONE,
[Description("Item Two Description")]
ITEM_TWO,
[Description("Item Three Description")]
ITEM_THREE
}
///
/// Main program to test functionality
///
class Program
{
///
/// Main program - Just prints out the values of the enumeration items
///
///
static void Main(string[] args)
{
// Create an instance of our enumeration and print to the console
MyCustomEnumeration myEnum = MyCustomEnumeration.ITEM_ONE;
Console.WriteLine(myEnum.ToDescriptionString());
// Did you know you could increment an enumeration? Sure you did!
myEnum++;
Console.WriteLine(myEnum.ToDescriptionString());
myEnum++;
Console.WriteLine(myEnum.ToDescriptionString());
}
}
}