Sunday, April 29, 2012

Using description attribute class with enums

Enums are very useful way to make constant strongly typed replacements for magic numbers/string that are also self-documenting, the down side is they can be a little limiting, to solve this we can use class attributes and extension methods to get more out of them.

Adding a description to a Enum is fairly easy just use the System.ComponentModel.DescriptionAttribute class to add descriptions to the enum values
   1: public enum BuildingTypes
   2: {
   3:     [Description("Retail Space")]
   4:     RetailSpace=1,
   5:     [Description("Office Space")]
   6:     OfficeSpace=2,
   7:     [Description("Single Family Residence")]
   8:     SingleFamilyResidence=3,
   9:     [Description("Multi Family Residence")]
  10:     MultiFamilyResidence=4,
  11:     [Description("Warehouse")]
  12:     Warehouse =5,
  13:     [Description("Manufacturing")]
  14:     Manufacturing =6
  15: }

In order to get the descriptions from the enum we need to do a little reflection and wrap it up in an extension method
   1: public static string ToDiscription(this Enum value)
   2: {
   3:     var description = string.Empty;
   4:     FieldInfo fi = value.GetType().GetField(value.ToString());
   5:  
   6:     var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),false);
   7:  
   8:     if (attributes != null && attributes.Length > 0)
   9:     {
  10:         description = attributes[0].Description;
  11:     }
  12:     else
  13:     {
  14:         description = value.ToString();
  15:     }
  16:     return description;
  17: }
Simple as that, for the full source see my sample code repository

No comments: