Is there anything in the .NET framework to convert a string representation
of an enum constant to it's value?

For example, given the following enum

    namespace Company.Product
    {
        public enum Options
        {
            One = 1,
            Two = 2,
            Three = 3
        }
    }

Is there any method that when given the string "Company.Product.Options.Two"
as input will return the value 2 as output? Enum.Parse doesn't exactly
qualify as it requires knowing the enum's type in advance. Well, it could be
used if the type is first extracted from the string and searched for in the
loaded assemblies. For example,

int ConvertEnumToInt32 ( string expression )
{
    int index = expression.LastIndexOf( '.' );
    if ( index > 0 )
    {
        Type type = null;
        string typeName = expression.Substring( 0, index );
        foreach ( Assembly assembly in
                                    AppDomain.CurrentDomain.GetAssemblies( ))
        {
            type = assembly.GetType( typeName );
            if ( type != null )
            {
                return ( int ) Enum.Parse(
                    type, expression.Substring( index + 1 ) );
            }
        }
    }
    throw new ArgumentOutOfRangeException( "expression", expression );
}

The preceding code works but I wonder if there is a more direct route. For
instance, is enumerating the loaded assemblies and calling GetType on each
an appropiate mechanism to search for the enum's type? Also, I suppose the
code would fail if the enum is defined in a referenced assembly which hasn't
been loaded yet. Are there any alternatives? Does parsing the name of the
enum's type and the constant's name by splitting the string at the last '.'
character cover every possible case?

Fernando Tubio

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to