Created
October 6, 2015 01:03
-
-
Save droyad/2891df7c221c897a8b8c to your computer and use it in GitHub Desktop.
Enum Extensions
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 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