Skip to content

Instantly share code, notes, and snippets.

@droyad
Created October 6, 2015 01:03
Show Gist options
  • Save droyad/2891df7c221c897a8b8c to your computer and use it in GitHub Desktop.
Save droyad/2891df7c221c897a8b8c to your computer and use it in GitHub Desktop.
Enum Extensions
public static class EnumExtensions
{
public static string ToDescription(this Enum enumValue)
{
if (enumValue == null)
return null;
var memInfo = enumValue.GetType().GetMember(enumValue.ToString());
var description = (DescriptionAttribute)memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
return (description == null)
? enumValue.ToString()
: description.Description;
}
public static T ToEnum<T>(this string value)
{
return (T)ToEnum(value, typeof(T));
}
public static T? ToNullableEnum<T>(this string value) where T : struct
{
return value?.ToEnum<T>();
}
public static object ToEnum(this string value, Type type)
{
var result = Enum.GetValues(type)
.Cast<Enum>()
.First(v => string.Equals(value, v.ToDescription()));
if (result == null)
throw new ArgumentException("Could not convert " + value + " to an enum", "value");
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment