Using a Description Attribute with Enumerations

Share on Facebook

Simple extension class to help use the description attribute with enumeration instances

public static class Extensions
    {
        public static string ToDescriptionString(this Enum currentEnum)
        {
            var fi = currentEnum.GetType().GetField(currentEnum.ToString());
            var da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
            return da != null ? da.Description : currentEnum.ToString();
        }

        public static object ParseWithDescriptionAttribute(this System.Enum value, string valueToParse)
        {
            //Get the Description String Attribute if any exists on the enum value
            string descString = value.ToDescriptionString();
            if (descString == valueToParse || value.ToString() == valueToParse)
            {
                return Enum.Parse(value.GetType(), value.ToString());
            }
            else return null;
        }
    }
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListkick it on DotNetKicks.comTwitThis

Comments are closed

About Me

When not scratching my head for solutions to software challenges, I spend my time playing with my little boy - Michael Jnr.

Quotations

"Every day I remind myself that my inner and outer life are based on the labors of other men, living and dead, and that I must exert myself in order to give in the same measure as I have received and am still receiving"
Albert Einstein

Donate with PayPal - it

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2005 - 2012

Search