Created
January 27, 2020 19:23
-
-
Save flakey-bit/c1293068c69dc32741e66cc206dab1eb to your computer and use it in GitHub Desktop.
To/From description methods for enums
This file contains 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 class EnumExtensions | |
{ | |
public static T GetAttribute<T>(this Enum value) where T : Attribute | |
{ | |
var type = value.GetType(); | |
var memberInfo = type.GetMember(value.ToString()); | |
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false); | |
return attributes.Length > 0 | |
? (T)attributes[0] | |
: null; | |
} | |
public static string ToDescription(this Enum value) | |
{ | |
var attribute = value.GetAttribute<DescriptionAttribute>(); | |
return attribute == null ? value.ToString() : attribute.Description; | |
} | |
public static Enum FromDescription(this string value, Type enumType) | |
{ | |
foreach (Enum enumValue in Enum.GetValues(enumType)) | |
{ | |
// First with matching description wins. | |
if (value == enumValue.ToDescription()) | |
{ | |
return enumValue; | |
} | |
} | |
throw new InvalidOperationException( | |
$"Could not parse value '{value}' as description for enum {enumType.Name}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment