I like enums, but sometimes I wish I could provide a better mechanism for getting the descriptive name for the enum.
I did a search for better mechanisms and really like the result I found at http://www.dotnet247.com/247reference/msgs/49/249710.aspx.
Basically, you use the [Description(”Description”)] attribute to put the description into the enum. Note that the Description attribute could also contain a resource string identifier, so that you could easily do localization.
Nice and neat. Keeps the description with the enum, and is better than a case statement, since the description is with the enum, so maintenance is easier.
Kudos to Nicholas Paldino [.NET/C# MVP].
Here’s a more robust version of the function that he proposes in his article (you’ll need to add
using System.Reflection;
using System.ComponentModel;
):
/// <summary>
/// Returns a string containing the description attribute value or the enum's name if no description is provided or tostring
/// if the object is not an enum. Note that if you call this function without passing an enum, you'll have a performance penalty
/// because of exception handling. The to string method will be called and you'll get a string result, but it'll be slow.
/// </summary>
/// <param name="value">The enum value for which to get the description.</param>
/// <returns>a string containing the description attribute value or the enum's name if no description is provided or tostring
/// if the object is not an enum.</returns>
public static string GetEnumValueDescription(object value)
{
string result=string.empy;
if (value != null)
{
result=value.ToString();
// Get the type from the object.
Type type = value.GetType();
try
{
result=Enum.GetName(type,value);
// Get the member on the type that corresponds to the value passed in.
FieldInfo fieldInfo = type.GetField(result);
// Now get the attribute on the field.
object[] attributeArray=fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute),false);
DescriptionAttribute attribute=null;
if (attributeArray.Length > 0)
{
attribute = (DescriptionAttribute)attributeArray[0];
}
if (attribute!=null)
{
result=attribute.Description;
}
}
catch (ArgumentNullException)
{
//We shouldn't ever get here, but it means that value was null, so we'll just go with the default.
result=string.empty
}
catch (ArgumentException)
{
//we didn't have an enum.
result=value.ToString();
}
}
// Return the description.
return result;
}