Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

TIP: Descriptions for enum values

Rate me:
Please Sign up or sign in to vote.
4.86/5 (4 votes)
24 Sep 2010CPOL 5.4K   3  
You could also make an extension method...public static class EnumExtensions{ public static string Description(this Enum e) { return e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[])[0].Description; ...
You could also make an extension method...

C#
public static class EnumExtensions
{
    public static string Description(this Enum e)
    {
        return e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[])[0].Description;
    }
}


Then the code to use is as simple as:

C#
public enum SampleEnum
{
    [Description("Value 1")]
    One,
    [Description("Value 2")]
    Two,
    [Description("Value 3")]
    Three
}

SampleEnum val = SampleEnum.One;

string desc = val.Description();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President 6D Systems LLC
United States United States
I studied Software Engineering at Milwaukee School of Engineering for 2 years before switching to Management of Information Systems for a more business oriented approach. I've been developing software since the age of 14, and have waded through languages such as QBasic, TrueBasic, C, C++, Java, VB6, VB.NET, C#, etc. I've been developing professionally since 2002 in .NET.

Comments and Discussions

 
-- There are no messages in this forum --