Enum With Custom Values In C#

Designer

Code Behind
using System.ComponentModel;
using System.Reflection;

public enum Test
{
    [DescriptionAttribute("Alphabet")]
     ABCD
};

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

protected void btnShow_Click(object sender, EventArgs e)
{
    Response.Write(stringValueOf(Test.ABCD));
}

Ref1, Ref2

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More