Return to Snippet

Revision: 61999
at January 26, 2013 21:29 by dimitrisdapontes


Updated Code
using System.Reflection;
using System.ComponentModel;

/// <summary>
/// Returns the enum description (if any), otherwise returns the name of the enum value
/// </summary>    
internal static string GetEnumDescription<TEnum>(TEnum enumObj)
{
    FieldInfo fi = enumObj.GetType().GetField(enumObj.ToString());
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return enumObj.ToString();
    }
}

Revision: 61998
at January 26, 2013 21:28 by dimitrisdapontes


Initial Code
/// <summary>
/// Returns the enum description (if any), otherwise returns the name of the enum value
/// </summary>    
internal static string GetEnumDescription<TEnum>(TEnum enumObj)
{
    FieldInfo fi = enumObj.GetType().GetField(enumObj.ToString());
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return enumObj.ToString();
    }
}

Initial URL


Initial Description
<p>Returns the description set in an enum value, or if not description is found it returns the name of the enum value. Use this without worrying about passing the enum type, you should only pass the enum value</p>

<p>Example</p>

<pre><code>internal enum Duration
{
    [Description("Every 12 Months")] Year = 1
    [Description("Every 6 Months")] Semester = 2
}

GetEnumDescription(Duration.Year) returns "Every 12 Months"
</code></pre>

Initial Title
Enum Description

Initial Tags


Initial Language
C#