McKelt.com

Remembering Thoughts

 

Recent comments

Authors

Categories


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Enum extension methods

public static class EnumExtensionMethods
    {

        public static T ParseAsEnumByDescriptionAttribute<T>(this string description)  // where T : enum
        {    
            if (string.IsNullOrEmpty(description))   
            {        
                throw new ArgumentNullException (description,@"Cannot parse an empty description");    
            }    

            Type enumType = typeof(T); 
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException (string.Format("Invalid Enum type{0}",typeof(T)));
            }   

            foreach (T item in Enum.GetValues(typeof(T)))
            {
                DescriptionAttribute[] attributes = (DescriptionAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0 && attributes[0].Description.ToUpper() == description.ToUpper())
                {
                    return item;
                }
            }
            throw new InvalidOperationException(string.Format("Couldn't find enum of type {0} with attribute of '{1}'", typeof(T),description));
        }
        
        public static string GetDescription(this Enum enumerationValue)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[]) enumerationValue.GetType().GetField(enumerationValue.ToString()).GetCustomAttributes(typeof (DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : enumerationValue.ToString();
        }

        public static EnumDto GetDto(this Enum enumerationValue)
        {
            return new EnumDto {Value = enumerationValue, Description = GetDescription(enumerationValue)};
        }

        public static T ToEnum<T>(this string enumerationString)
        {
            return (T) Enum.Parse(typeof (T), enumerationString);
        }

Posted by chris on Friday, October 23, 2009 6:33 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading