Skip to content

Instantly share code, notes, and snippets.

@flakey-bit
Created January 27, 2020 19:23
Show Gist options
  • Save flakey-bit/c1293068c69dc32741e66cc206dab1eb to your computer and use it in GitHub Desktop.
Save flakey-bit/c1293068c69dc32741e66cc206dab1eb to your computer and use it in GitHub Desktop.
To/From description methods for enums
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