Tuesday, April 7, 2015

ASP.Net C# Extension Method to get Enum Description

Ever needed to get the Description attribute from an enum in C#? Here's an easy way to do it generically with an extension method.

Enum:
 public enum Menu  
 {  
      Home,  
      [Description("About Page Description")]  
      About,  
      [Description("Contact Page Description")]  
      Contact  
 }  

Code:
 public static string Description(this Enum value)  
 {  
      // variables  
      var enumType = value.GetType();  
      var field = enumType.GetField(value.ToString());  
      var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);  
   
      // return  
      return attributes.Length == 0 ? value.ToString() : ((DescriptionAttribute)attributes[0]).Description;  
 }  

Example usage:
 string Description = Enumerators.Menu.About.Description();  

In this case Description variable would be set to the string value "About Page Description". If the enum property you are accessing doesn't have a Description attribute the extension method will return the value of the enum instead.

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

1 comment: