Extension Methods with Enum Description

Since Enum names in .NET do not support certain characters like spaces, often developers will use the DescriptionAttribute to add detailed text to an Enum. 

   [Flags]
   internal enum SuperHero 
   {
      [Description("Clark Kent")]
      Superman = 1,
      [Description("Peter Parker")]
      SpiderMan = 2,
      [Description("Bruce Banner")]
      Hulk = 4,
      [Description("Tony Stark")]
      IronMan = 8,
   }

You can pull the description from the enum with code like this.  (Keep in mind that you can make this MUCH faster using DynamicMethods and caching, but that is another article…)

      private const char ENUM_SEPERATOR_CHARACTER = ',';
      public static string GetDescription(Enum value)
      {
         // Check for Enum that is marked with FlagAttribute
         var entries = value.ToString().Split(ENUM_SEPERATOR_CHARACTER);
         var description = new string[entries.Length];
         for (var i = 0; i < entries.Length; i++)
         {
            var fieldInfo = value.GetType().GetField(entries[i].Trim());
            var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            description[i] = (attributes.Length > 0) ? attributes[0].Description : entries[i].Trim();
         }
         return String.Join(", ", description);
      }

Well, now with .NET 3.5 and Extension methods it only makes sense to make this a little bit easier.

      public static string Description(this Enum value)
      {
         return GetDescription(value);
      }

And now you can do the following:

         var secretIdentity = SuperHero.Superman.Description();
         var superHeroes = SuperHero.Superman | SuperHero.SpiderMan;
         var secretIdentities = superHeroes.Description();

Note that the code handles Enum marked with the FlagAttribute as well.  The output of the whole flag thing is not ideal but at least it does not break when handling those Enums.

Brenton House

2 Comments

  • Just one tip so eveyone is aware: when youre using both xml comments and DescriptionAttribute, the former will have presedence over the latter.

    In a quick example, using this enum:
    public enum API
    {
    ///
    /// Using Google API
    ///
    [Description("Google API")]
    Google = 1,
    ///
    /// Using Yahoo API
    ///
    [Description("Yahoo API")]
    Yahoo = 2
    }

    and calling API.Yahoo.Description() will yield "Using Yahoo API".

  • How would you write a DynamicMethod for this? &nbsp;I'm new to them, and not sure how it would work.

Comments have been disabled for this content.