Created
April 6, 2014 09:44
-
-
Save curzona/10003743 to your computer and use it in GitHub Desktop.
Adding Descriptions to your Enumerations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // From http://www.codeproject.com/Articles/13821/Adding-Descriptions-to-your-Enumerations | |
| public class EnumUtils<T> | |
| { | |
| public static string GetDescription(T enumValue, string defDesc) | |
| { | |
| FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString()); | |
| if (null != fi) | |
| { | |
| object[] attrs = fi.GetCustomAttributes | |
| (typeof(DescriptionAttribute), true); | |
| if (attrs != null && attrs.Length > 0) | |
| return ((DescriptionAttribute)attrs[0]).Description; | |
| } | |
| return defDesc; | |
| } | |
| public static string GetDescription(T enumValue) | |
| { | |
| return GetDescription(enumValue, string.Empty); | |
| } | |
| public static T FromDescription(string description) | |
| { | |
| Type t = typeof(T); | |
| foreach (FieldInfo fi in t.GetFields()) | |
| { | |
| object[] attrs = fi.GetCustomAttributes | |
| (typeof(DescriptionAttribute), true); | |
| if (attrs != null && attrs.Length > 0) | |
| { | |
| foreach (DescriptionAttribute attr in attrs) | |
| { | |
| if (attr.Description.Equals(description)) | |
| return (T)fi.GetValue(null); | |
| } | |
| } | |
| } | |
| return default(T); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment