What you will do if you asked to get a description of your defined Enum?
Here is a simplest way, just need to define an extension method:
We have following defined Enum:
- public enum AuthorLevels
- {
- [Description("No level")]
- None,
- Description("Starter")]
- Bronze,
- [Description("Intermediate")]
- Golden,
- [Description("Advance")]
- Platinum
- }
Define an extension method:
- public static class EnumExtensionMethods
- {
- public static string GetEnumDescription(this Enum enumValue)
- {
- var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
-
- var descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
-
- return descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : enumValue.ToString();
- }
- }
Do not forget to add following namespace, in above:
- using System.ComponentModel;
Now, call this extension method as:
- var authorLevel = AuthorLevels.Platinum.GetEnumDescription();
Above will give you: 'Advance'.
Enjoy :)