Skip to content

Instantly share code, notes, and snippets.

@rdakar
Created July 2, 2017 22:14
Show Gist options
  • Save rdakar/9e7f21cd6e085dbdfefda42a3386b254 to your computer and use it in GitHub Desktop.
Save rdakar/9e7f21cd6e085dbdfefda42a3386b254 to your computer and use it in GitHub Desktop.
EnumExtender.GetEnumValue
public static T GetEnumValue<T>(this string description)
{
var type = typeof(T);
if (!type.GetTypeInfo().IsEnum)
throw new ArgumentException();
var field = type.GetFields().SelectMany(f => f.GetCustomAttributes(typeof(DescriptionAttribute), false), (f, a) => new { Field = f, Att = a })
.Where(a => ((DescriptionAttribute)a.Att).Description == description).SingleOrDefault();
return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment