CodeCloudy

Azure | .Net | JQuery | Javascript | Umbraco

How to Expose a Description for Enums

Step1: add a description tag to the enums.

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

Step 2: Create an common class. (eg: Common or ExtentionMethods). Then add the following methods.

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);
      }
 public static string Description(this Enum value)
      {
         return GetDescription(value);
      }

Step 3: Add a reference to you extension class.

example: using YourNamespace.Common;

Step 4: Use it where you need it.

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

if you are using Razor:

@YourEnum.Description()

Leave a comment »