Monday, March 14, 2011

Enums with string values

Many times I've wanted to have enums, that can be represented in both numeric(integer) form and string form. The problem with ToString method is that it is sometimes in not human friendly. For example if I've an enum called "Language" and "ZnCH" as one of its values. Now, lets suppose we want to show users the list of languages available in the site. Using in-built ToString method will just show "ZnCH", while we may be wanting then to see "Simplified Chinese".

Without boring you further let's see how to implement it. We will use System.ComponentModel.DescriptionAttribute to store the string value, and extension method to retrieve the string value. Here's the code
using System;
using System.ComponentModel;

public enum Language : int
{
  [Description("English")]
  EnUS = 1,
  [Description("Simplified chinese")]
  ZhCN = 2
}

public static class EnumExtensions
{
  public static string ToString(this Enum enumInput, bool showFromDescription)
  {
    if (showFromDescription)
    {
      DescriptionAttribute[] descAttributes = (DescriptionAttribute[])enumInput.GetType().GetField(enumInput.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
      if (descAttributes.Length > 0)
      {
        if (!string.IsNullOrWhiteSpace(descAttributes[0].Description))
        {
          return descAttributes[0].Description;
        }
      }
    }
    return enumInput.ToString();
  }
}

public class Program
{
  public static void Main(params string[] args)
  {
    Language lang = Language.ZhCN;
    Console.WriteLine(lang.ToString(true));//outputs "Simplified Chinese"
  }
}