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)
                {
                    Log1.log(anEnumeratedValue);
                    return anEnumeratedValue;
                }
            }
            string aNameToLookFor = obj.ToString();
            return (T)Enum.Parse(typeof(T), aNameToLookFor, ignoreCase: true);
        } 
#END
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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