Sunday, June 12, 2016

Get description Attributes from Enum.

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
         //Get Description
            Console.WriteLine(GetEnumDescription<MyEnum>(2));

            //Get Value
            Console.WriteLine(MyEnum.Hear);

            //Get Name
            Console.WriteLine(Enum.GetName(typeof(MyEnum), 1));

            //Get Enum Descriptions values
            var myEnumDescriptions =
                Enum.GetValues(typeof(MyEnum))
                    .Cast<MyEnum>()
                    .Select(n => new { ID = (int)n, Name = Enum.GetName(typeof(MyEnum), n), Description = GetEnumDescription(n) });

            //Get Name, Description, Value
            foreach (var item in myEnumDescriptions)
            {
                Console.WriteLine(item.Name);
            }

            //Iterate and fetch Description
            foreach (int iValues in Enum.GetValues(typeof(MyEnum)))
            {
                Console.WriteLine(GetEnumDescription <MyEnum>(iValues));
            }
        }

        public enum MyEnum
        {
            [Description("You can Walk")]
            Walk = 1,
            [Description("You can Talk")]
            Talk = 2,
            [Description("You can Hear")]
            Hear = 3
        }

        public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false);

            if (attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }

        public static string GetEnumDescription <T>(int value)
        {
            return GetEnumDescription((Enum)(object)((T)(object)value));
        }
    }


}



No comments :