PackUtils/EnumUtility.cs
/// <summary>
/// Get enum from description - if not found, returns default
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
/// <param name="description">description</param>
/// <param name="notFoundReturnDefault">description</param>
/// <returns></returns>
Get enum from description - if not found, returns default
Get enum from description - if not found returns default
public static T GetEnumFromDescription<T>(string description, bool notFoundReturnDefault)
        {
            var type = typeof(T);
            if (!type.IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type.");
            }
            foreach (var field in type.GetFields())
            {
                DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attribute != null)
                {
                    if (attribute.Description == description)
                    {
                        return (T)field.GetValue(null);
                    }
                }
            }
            if (notFoundReturnDefault == true)
            {
                return default(T);
            }
            throw new KeyNotFoundException(description + " not found in " + typeof(T).Name);
        }
public static T GetEnumFromDescription < T > ( string description , bool notFoundReturnDefault ) { var type = typeof ( T ) ; if ( ! type . IsEnum ) { throw new ArgumentException ( " " ) ; } foreach ( var field in type . GetFields ( ) ) { DescriptionAttribute attribute = Attribute . GetCustomAttribute ( field , typeof ( DescriptionAttribute ) ) as DescriptionAttribute ; if ( attribute != null ) { if ( attribute . Description == description ) { return ( T ) field . GetValue ( null ) ; } } } if ( notFoundReturnDefault == true ) { return default ( T ) ; } throw new KeyNotFoundException ( description + " " + typeof ( T ) . Name ) ; }
Get enum from description - if not found, returns default
Get enum from description - if not found returns default
None
description
string
None
notFoundReturnDefault
bool
None
typeparam
None