Combining Enums and Attributes

Enums are a porwerful and simple way to define standard and expected values. Enums can be easily linked with the database by storing the values as numbers or with XML data by storing the value names as text. The values can be easily converted and parsed both ways using the functions of the Enum class.

Linking enum values with the user interface is more tricky. Longer enum names are not very user friendly so you don’t want to display them directly. Combining attributes with your enums offers a flexible way to control how your enums are presented to the user.

First you need a custom attribute to decorate the values definitions with:

[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = false)]
public class EnumDescriptionAttribute : Attribute
{
   public EnumDescriptionAttribute(string description)
   {
      Description = description;
   }

   public string Description { get; set; }
}

Then use your attribute to decorate your enums like this:

public enum PowerConsumtion { 
   [
EnumDescriptionAttribute(“Full power”)]
   High,
   [EnumDescriptionAttribute(“Energy saver”)]
   Low
}

Then all you need is a function extending the features of the Enum.GetNames() to return the user friendly names:

public static string[] GetNames(Type enumType, string group)
{
   List<string> names = new List<string>();
   Type type = enumType;

   FieldInfo[] fields = type.GetFields();

   for (int i = 1; i < fields.Length; i++)
   {
      FieldInfo field = fields[i];
      EnumDescriptionAttribute attribute = GetDescription(field);

      string descrption = field.Name;

      if (attribute != null)
      {
         if (attribute.Description != null)
            descrption = attribute.Description;
      }

      names.Add(descrption);
   }

   return names.ToArray();
}

private static EnumDescriptionAttribute GetDescription(FieldInfo field)
{
   EnumDescriptionAttribute[] attributes = field.GetCustomAttributes(typeof(EnumDescriptionAttribute), false) as EnumDescriptionAttribute
[];    
  
   if (attributes != null && attributes.Length > 0)
   {
      return attributes[0];
   }
   else
   {
      return null;
   }
}

 

You can now use the attributes to help you decorate the values with any kind of information. I usually have properties for hiding and groupping values. 

Advertisements

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