using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace Church.Net.Utility { public static class EnumHelper { public static string EnumToDescriptionString(this Enum val) { //pull out first value in case of flag enumeration var firstValue = val.ToString().Split(',').Select(s => s.Trim()).First(); IEnumerable attributes = val .GetType() .GetField(firstValue) .GetCustomAttributes(false); return true == attributes?.Any() ? attributes.First().Description : val.ToString(); } public static T GetEnumValueFromDescription(string description) where T : struct { object value = GetEnumValueFromDescription(typeof(T), description); return value is null ? default : (T)value; } public static object GetEnumValueFromDescription(Type type, string description) { if (type is null) return null; if (!type.IsEnum) { if (type.IsNullableEnum()) { type = Nullable.GetUnderlyingType(type); } else { throw new ArgumentException(); } } FieldInfo field = type.GetFields() .FirstOrDefault(f => f.GetCustomAttributes(false) .FirstOrDefault(a => a.Description == description) != null ) ; return field == null ? null : Enum.ToObject(type, field?.GetRawConstantValue()); return field?.GetRawConstantValue(); } public static bool IsNullableEnum(this Type t) { Type u = Nullable.GetUnderlyingType(t); return (u != null) && u.IsEnum; } public static TEnum GetDefaultEnumValue() where TEnum : struct { return (TEnum)GetDefaultEnumValue(typeof(TEnum)); } public static object GetDefaultEnumValue(Type type) { if (type is null) return null; IEnumerable attributes = type.GetCustomAttributes(false); return attributes?.FirstOrDefault()?.Value; } } }