Enums and strings

Hello everybody,

I want to share some pieces of code how to work with enums. 

Some time it is needed to have list of string constants in your code, which can feet to some strings with spaces. 

enum EarningType
    {
        [Description("Virginina")]
        VL,
        [Description("Salt and Lasso")]
        SL,
        [Description("TO")]
        TO,
        [Description("RG")]
        RG
    }

One of easy ways to use description is usage of extension methods like this:

 public static class EnumsProcessor
    {
        public static string GetEnumDescription(this Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());

            var attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
                return attributes[0].Description;
            return value.ToString();
        }
}

and then in code you can write something like this:

EarningType.VL.GetEnumDescription() which will return you description from description field.

No Comments

Add a Comment