Gets the Description for a given enum value - CSharp System.Reflection

CSharp examples for System.Reflection:Type

Description

Gets the Description for a given enum value

Demo Code


using System.Reflection;
using System.Linq.Expressions;
using System.Linq;
using System.ComponentModel;
using System;//www  .  ja v a  2s  . c o m

public class Main{
        /// <summary>
        /// Gets the Description for a given enum value
        /// </summary>
        /// <param name="value">Enum item</param>
        /// <returns>The description of the item or the enum casted to string</returns>
        public static string GetEnumDescription(Enum value)
        {
            var attribute = value.GetType()
                                 .GetField(value.ToString())
                                 .GetCustomAttributes(typeof(DescriptionAttribute), false)
                                 .SingleOrDefault() as DescriptionAttribute;

            return attribute == null ? value.ToString() : attribute.Description;
        }
}

Related Tutorials