Friday, April 20, 2012

Quick Tip: Enum Descriptions / Labels

If you ever had an enumerable list but wanted to include 'friendly names' with the list, this is how you can do it using Extension methods.

Create an extension Method
public static string Description(this Enum enumValue)

var enumType = enumValue.GetType();
var field = enumType.GetField(enumValue.ToString());
var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length == 0 ? enumValue.ToString() : ((DescriptionAttribute)attributes[0]).Description;
Define an Enum
public enum AnEnum
Use the enum
var displayName = AnEnum.Val1.Description();

No comments:

Post a Comment