How do I get an Enum value from a Description Attribute

Kumara_Sanjaya
Kumara_Sanjaya used Ask the Experts™
on
Hi,
I have a Enumeration helper class which returns the Description Attribute of an Enum.
(Code Posted below)
I want to get the enumerated value from the description. How do I do it?
I copied some code from the earlier answers, but the usage is a big problem. I am unable to get it working. Kindly help out
public static class EnumerationHelper
    {
        public static string GetEnumDescription(Enum en)
        {
            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if(memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof (Description), false);
                if(attrs != null && attrs.Length > 0)
                {
                    return ((Description) attrs[0]).Text;
                }
            }
            return en.ToString();
        }
 
 
        public static Enum GetEnumValueFromDescription(Type MyType, string Description)
        {
            Enum retEnumValue = null;
 
            foreach (Enum e in Enum.GetValues(MyType))
            {
                string sValue = GetEnumDescription((Enum)e);
                if (sValue.ToLower() == Description.ToLower())
                {
                    retEnumValue = e;
                    break;
                }
            }
 
            return retEnumValue;
        }
 
    }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you might try this

Enum Days
        Saturday
        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
    End Enum 'Days

For Each s In  [Enum].GetNames(weekdays)
            Console.WriteLine("{0,-11} = {1}", s, [Enum].Format(weekdays, [Enum].Parse(weekdays, s), "d"))
        Next s
This will produce the names of the week and their corresponding values of the Days
from what i understand you're basically trying to do the same thing as the StringValue attribute in this codeplex article.  I've done the code you have posted above, but his helper classes also revert back, which is pretty handy.

http://www.codeproject.com/KB/cs/stringenum.aspx
lol, look at that.. i said codeplex, but the article is from code project.. my bad
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

The example was from Vb 2008 help file and can go both ways if needed
so if you thought it was my code I should have said it came from vb help files

Commented:
Please put sample enum over here.
oh wow.. i'm a dolt...  your code already has the method in it to get the enumeration from the description.
If you have the text you should just have to do this:

enum MyEnum
{
    [Description("Enum One")]
    Enum1,

    [Description("Enum Two")]
    Enum2
}


public class MyClass
{
    public MyClass()
    {
        MyEnum myEnum = EnumerationHelper.GetEnumValueFromDescription(typeof(MyEnum), "Enum One") as MyEnum;
    }
}

what could be even more helpful would be to make the GetEnumValueFromDescription a generic method (if you're using .NET 2.0 or higher) but the code above should work
I know it's been a whiles sense I have posted but I  have posted the information what was requested so if "Bookmark" needs more information he should say so and I will be glad  to provide the information requested.  If you have code to add I welcome the input
sorry if this cause any grief

Author

Commented:
Hi,
Thanks for the efforts. However, in the folllowing solution, there is a problem:
public class MyClass
{
    public MyClass()
    {
        MyEnum myEnum = EnumerationHelper.GetEnumValueFromDescription(typeof(MyEnum), "Enum One") as MyEnum;
    }
}

The compiler complains that "as" operator can be applied only to reference types and not value types

Kindly clarify
Regards
Dr. Kumara Sanjaya
Commented:

public class MyClass
{
    public MyClass()
    {
        MyEnum myEnum = (NyWnum)EnumerationHelper.GetEnumValueFromDescription(typeof(MyEnum), "Enum One");
    }
}

Open in new window

Author

Commented:
Thank you very much. That solved my problem.

Author

Commented:
Thanks for the answer from jinal. I also learnt another method and I am posting the code for everyone's benefit

 public static class EnumerationHelper
    {
        public static string GetEnumDescription(Enum en)
        {
            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if(memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof (Description), false);
                if(attrs != null && attrs.Length > 0)
                {
                    return ((Description) attrs[0]).Text;
                }
            }
            return en.ToString();
        }


        public static Enum GetEnumValueFromDescription(Type MyType, string Description)
        {
            Enum retEnumValue = null;

            foreach (Enum e in Enum.GetValues(MyType))
            {
                string sValue = GetEnumDescription((Enum)e);
                if (sValue.ToLower() == Description.ToLower())
                {
                    retEnumValue = e;
                    break;
                }
            }

            return retEnumValue;
        }

        public static object Parse(Type type, string stringValue, bool ignoreCase)
        {
            object output = null;
            string enumStringValue = null;

            if (!type.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type.ToString()));

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in type.GetFields())
            {
                //Check for our custom attribute
               Description[] attrs = fi.GetCustomAttributes(typeof(Description), false) as Description[];
                if (attrs != null)
                    if (attrs.Length > 0)
                        enumStringValue = attrs[0].Text;

                //Check for equality then select actual enum value.
                if (string.Compare(enumStringValue, stringValue, ignoreCase) != 0) continue;
                output = Enum.Parse(type, fi.Name);
                break;
            }

            return output;
        }

    }
wow, no partial marks because i had the wrong type of cast?  that's rough

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial