Created
July 2, 2017 22:14
-
-
Save rdakar/9e7f21cd6e085dbdfefda42a3386b254 to your computer and use it in GitHub Desktop.
EnumExtender.GetEnumValue
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
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