You will need to iterate over all the static enumeration fields (how they are stored in the reflection), finding the Description attribute for each of them ... when you notice the correct one, get the field value.
For instance:
public static T GetValue<T>(string description) { foreach (var field in typeof(T).GetFields()) { var descriptions = (DescriptionAttribute[]) field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (descriptions.Any(x => x.Description == description)) { return (T) field.GetValue(null); } } throw new SomeException("Description not found"); }
(It is common to make it reusable for various transfers.)
Obviously, you want to cache descriptions if you do this even a little often, for example:
public static class DescriptionDictionary<T> where T : struct { private static readonly Dictionary<string, T> Map = new Dictionary<string, T>(); static DescriptionDictionary() { if (typeof(T).BaseType != typeof(Enum)) { throw new ArgumentException("Must only use with enums"); }
source share