Deal with it or don't

Enum GetDescription

So, wilsonhut of the future. You’ve come here to copy/paste this code again…

This one’s a slam dunk. You need a enum to be the values in a combo box or something, and you want the text of each option to be friendly text.

Consider this ridiculous enum:

public enum VanHalenSingers
  [Description("Diamond Dave")]
  [Description("The Red Rocker")]
  [Description("I Think That Is All")]

Now the code:

public static string GetDescription<T>(this T enumValue)
  if(Equals(enumValue, null))
    throw new ArgumentNullException("enumValue");
  if (!(enumValue is Enum))
    throw new ArgumentException("enumValue must be an Enum.");

  var memberInfos = enumValue.GetType().GetMember(enumValue.ToString());

  if (memberInfos != null && memberInfos.Length > 0)
    var attributes = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0)
      return ((DescriptionAttribute)attributes[0]).Description;
  return enumValue.ToString();

So you can call it like this:


That will output “Diamond Dave”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: