Geeks With Blogs
Scott Wojan DotRant BLOG

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;

        }

    }

 

Posted on Thursday, May 17, 2012 4:06 PM | Back to top

Copyright © Scott Wojan | Powered by: GeeksWithBlogs.net