Sunday, July 12, 2015

How to get enum description from enum C# using Dictionaries



using System;
using System.Linq;
using System.Reflection;
using Constants.EnumHelpers;

namespace EnumDescription
{
public enum OrderEnum
{
        [Description("Buy Market")]
        OT_buyMarket = 0,

        [Description("Sell Market")]
        OT_sellMarket,

        [Description("Buy Limit")]
        OT_buyLimit,

        [Description("Sell Limit")]
        OT_sellLimit,
}

public HowToGetEnumDescription
        {

        private static Dictionary<int, string> GetDictionaryFromEnum<T>()
        {
            var myDictionary = new Dictionary<int, string>();
            foreach (T code in Enum.GetValues(typeof(T)).Cast<T>())
            {
                if ((code as Enum).Lookup())
                {
                    myDictionary.Add(int.Parse((code as Enum).GetValue()), (code as Enum).GetDescription());
                }
            }

            return myDictionary;
        }

        private static string getEnumDescription(int roleKey) {
            Dictionary<int, string> defaultDictinary = GetDictionaryFromEnum<EnumDescription.OrderEnum>();
            string value;
            defaultDictinary.TryGetValue(roleKey, out value);
            return value;
        }
[TestMethod]
        public void TestingHowToGetEnumDescription()
        {
       Dictionary<int, string> selectedDictinary = GetDictionaryFromEnum<EnumDescription.OrderEnum>();
                Assert.IsNotNull(selectedDictinary);
                Assert.IsTrue(selectedDictinary.ContainsValue(getEnumDescription((int)EnumDescription.OrderEnum.OT_buyMarket)));
}
}

    public static class EnumHelper
    {
        public static string GetDescription(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            Description attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(Description)) as Description;
            return attribute == null ? value.ToString() : attribute.Text;
        }

        public static bool Lookup(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            Include attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(Include)) as Include;
            return attribute == null ? true : attribute.IncludeInLookup;
        }

        public static string GetValue(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            Value attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(Value)) as Value;
            return attribute == null ? Convert.ToInt32(value).ToString() : attribute.Text;
        }
    }


}