reflection on a c# enum instance



        /// An enum type
        /// Could be the enum name like OneDay or declared value like “1D”
        public static T StrToEnum(object obj)
            if (obj == null) throw new Exception();
            foreach (T anEnumeratedValue in GetValues())
                MemberInfo[] memInfoArray = typeof(T).GetMember(anEnumeratedValue.ToString());
                if (memInfoArray.Length == 0) break;
                object[] attributes = memInfoArray[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);
                if (attributes.Length == 0) break;
                string declaredValue = ((EnumMemberAttribute)attributes[0]).Value;
                if (obj.ToString() == declaredValue)
                    return anEnumeratedValue;
            string aNameToLookFor = obj.ToString();
            return (T)Enum.Parse(typeof(T), aNameToLookFor, ignoreCase: true);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s