C# Add Description attributes to Enumerations

Enumerations in C# (ASP or WinForms) are used extensively. And all too often we need to associate a description or attribute to each enumeration for output. This can be done in a large switch / case function. But here is a neater way.

Add [Description] attributes to you enumeration. This requires the  System.ComponentModel reference.

using System.ComponentModel;

public enum StatusCode
 {
 [Description("Successful API call")]
 Success = 0,

 [Description("Failure: The input was not numeric")]
 InputNotNumeric= 10,

 [Description("Failure: User not authenticated")]
 AuthenticationFailure = 20,
 }

Now the following function can be used in a generic utility class. This function accepts an enumeration value and returns the description attribute

public static string GetDescription<T>(this T value)
 {
 FieldInfo fi = value.GetType().GetField(value.ToString());
 if (fi != null)
 {
 object[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), true);
 if (attributes != null && attributes.Length > 0)
 {
 return ((DescriptionAttribute)attributes[0]).Description;
 }
 }
 return string.Empty;
 }

Now this an be used with any enumeration like this

 
string enumerationOutput = "";
 foreach (StatusCode statusCode in Enum.GetValues(typeof(StatusCode)))
 {
    enumerationOutput += ((int)statusCode).ToString() + "-" + GetDescription(statusCode)) + LineBreak;
 }

And this would output

0 - Successful API call
10- Failure: The input was not numeric
20-Failure: User not authenticated

Also now found this great article on this topic too:

http://blog.spontaneouspublicity.com/associating-strings-with-enums-in-c . Great minds… ;-)

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>