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();
            }
        }
    }

One thought on “Get Enum Description From Value in C#

  1. This solution creates a pair of extension methods on Enum. The first allows you to use reflection to retrieve any attribute associated with your value. The second specifically calls retrieves the

Leave a Reply to VideoPortal Cancel reply

Your email address will not be published. Required fields are marked *