Tuesday, February 13, 2007
by Thad Smith

I seem to use numerous Enumerated types and use these to fill in list boxes.  The problem is, a few of these types do not have a nice name for the user.  Problem solved, simply created a class that could decorate the enumeration and retun a text representation.

    [AttributeUsage(AttributeTargets.Field)]
    public class EnumTextAttribute : Attribute
    {
        private string text;
        public string Text
        {
            get { return text; }
        }

        public EnumTextAttribute(string text)
        {
             this.text = text;
        }
    }

    public static class EnumHelper
    {
        public static void IsEnumValid(Type enumType, object value)
        {
            if (!Enum.IsDefined(enumType, value))
                throw new Exception(value.ToString());
        }

        public static string GetText(Enum e)
        {
            FieldInfo fieldInfo = e.GetType().GetField(e.ToString());
            object[] attrs = fieldInfo.GetCustomAttributes(typeof(EnumTextAttribute), false);
            if (attrs.Length == 0)
                return e.ToString();
            else
                return ((EnumTextAttribute)attrs[0]).Text;
        }

        public static T GetValue<T>(string text)
        {
            MemberInfo[] members = typeof(T).GetMembers();
            foreach (MemberInfo mi in members)
            {
                object[] attrs = mi.GetCustomAttributes(typeof(EnumTextAttribute), false);
                if (attrs.Length == 1)
                {
                    if (((EnumTextAttribute)attrs[0]).Text == text)
                        return (T)Enum.Parse(typeof(T), mi.Name);
                }
                else
                {
                    if(mi.Name == text)
                        return (T)Enum.Parse(typeof(T), mi.Name);
                }
            }           
            throw new ArgumentOutOfRangeException("text", text, "The text passed does not correspond to an attributed enum value.");
        }
    }

 

With the above class I now define the enumeration as follows and use the EnumHelper class to translate between Text and Value.

    public enum DeliverByType
    {       
        None = 0,
        Mail,
        [EnumText("E-Mail")]
        Email, //E-Mail
       
[EnumText("Mail and E-Mail")]
        Both //Mail and E-mail
    }

Posted on Tuesday, February 13, 2007 10:19:32 AM (Eastern Standard Time, UTC-05:00)  #   Comments [0] | Trackback