Scott Wojan

DotRant BLOG
posts - 20 , comments - 70 , trackbacks - 5

Enum helper for values specified in attributes

I've used this enum helper from time to time to get an enum value from attributes such as Description and XmlEnumAttribute. Maybe you can find it useful?

    public static class EnumEx

    {

        public static T GetXmlEnumValue<T>(string name)

        {

            var type = CheckEnum<T>();

 

            var val = (from f in type.GetFields()

                       let attribute = f.GetCustomAttributes(typeof(System.Xml.Serialization.XmlEnumAttribute), true).FirstOrDefault() as System.Xml.Serialization.XmlEnumAttribute

                       where attribute != null

                          && attribute.Name == name

                       select (T)f.GetValue(null));

 

            if (val.Count() == 0)

                throw new ArgumentException(string.Format("{0} is not a valid XmlEnumAttribute for {1}", name, typeof(T).FullName), "name");

 

            return val.First();

        }

 

        public static T GetValueFromDescription<T>(string description)

        {

            var type = CheckEnum<T>();

 

            var val = (from f in type.GetFields()

                       let attribute = f.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true).FirstOrDefault() as System.ComponentModel.DescriptionAttribute

                       where attribute != null

                          && attribute.Description == description

                       select (T)f.GetValue(null));

 

            if (val.Count() == 0)

                throw new ArgumentException(string.Format("{0} is not a valid description for {1}", description, typeof(T).FullName), "description");

 

            return val.First();

        }

 

        private static Type CheckEnum<T>()

        {

            var type = typeof(T);

            if (type.IsEnum == false)

                throw new InvalidOperationException(string.Format("{0} is not an enum", typeof(T)));

            return type;

        }

    }

 

Print | posted on Thursday, May 17, 2012 4:06 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: