Monday, 23 February 2015

How to get Enum Description

For e.g:- If you a enum as follows:-

public enum EnumName
{
   [Description("Description1 of value1")]
   value1,
   [Description("Description2 of value2")]
   value2,
   [Description("Description3 of value3")]
   value3
}

//To fetch the description e.g["Description1 of value1"] from value1 of enum :-

using System;
using System.Reflection; // for FieldInfo 

using System.ComponentModel; // for DescriptionAttribute

static void Main(string[] args)
 {
            string desc1 = ToDescription(EnumName.value1);
            Console.WriteLine("the description is [value1]:" + desc1);
 EnumName val1=GetValueFromDescription<EnumName >(desc1);

           Console.WriteLine("the description is :" + val1);
}

//It will fetch description from enum value
 public static string ToDescription(object value)
  {
      FieldInfo field =value.GetType().GetField(value.ToString());
      DescriptionAttribute[] attributes =(DescriptionAttribute[])field
      .GetCustomAttributes(typeof(DescriptionAttribute), false);
       if (attributes.Length > 0)
        {
                return attributes[0].Description;
        }
            return value.ToString();
  }
//it will fetch value from description:-

 public static EnumName GetValueFromDescription<EnumName>(string description)
{
            var type = typeof(EnumName);
            if (!type.IsEnum) throw new InvalidOperationException();
            foreach (var field in type.GetFields())
            {
                var attribute = Attribute.GetCustomAttribute(field,
                    typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attribute != null)
                {
                    if (attribute.Description == description)
                        return (EnumName)field.GetValue(null);
                }
                else
                {
                    if (field.Name == description)
                    return (EnumName)field.GetValue(null);
                }
            }
            throw new ArgumentException("Not found.", "description");
            // or return default(call);

}



No comments:

Post a Comment