Enums And Strings

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("Salt and Lasso")]

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
Comments are closed