I'm looking for a way to lookup an enumeration field by providing it's display name. To lookup the display name I wrote this snipped which returns me the appropriate field (if available) as an arbitary type.
if (!type.IsEnum) throw new ArgumentException("type");
return (from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
where field.IsDefined(typeof(DisplayNameAttribute))
let attribute = field.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute
where attribute != null && attribute.DisplayName.Equals(lookup, StringComparison.InvariantCultureIgnoreCase)
select (T)field.GetValue(null)).FirstOrDefault();
Now, I would like to call it this way:
MyEnum instance = MyEnum.GetFieldByDisplayName("my friendly name");
I tried creating an extension method that takes "this Type
" as well as "this Enum
" as parameter, but it never shows up on MyEnum. What am I doing wrong?