17 Jun

Get Enum Description From Value in C#

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. We can define the attributes for enum and if you want to fetch these description simply, we can use as shown below.

Usage:

            string description = EnumHelper.StringValueOf(SiteType.Technology);
            Console.WriteLine(description);
            //Output:
            //This is a technology site.

Sample Code:

    public class EnumHelper
    {
        public static string StringValueOf(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();
            }
        }
    }