-3

I have this enum:

public enum SomeEnum
{
   None,
   Half,
   All
}

How would be the following method body, so I can get the value 1 have option "None" and enum name "SomeEnum" stored as string:

string enumTypeName = "SomeEnum";
string enumPickedOptionName = "None";

Method:

public int GetEnumValue(string enumTypeName, string enumPickedOptionName){}
Raphael Ribeiro
  • 529
  • 5
  • 18

2 Answers2

1

Try this out using the "Namespace" before the enumeration name:

private int GetEnumValue(string enumTypeName, string enumPickedOptionName)
    {
        int result = -1;
        Type enumType;

        try
        {
            enumType= Type.GetType(enumTypeName);
            result = (int)Enum.Parse(enumType, enumPickedOptionName,true);
        }
        catch (Exception ex)
        {

        }
        finally
        {

        }

        return result;
    }

int value = GetEnumValue("Namespace.SomeEnum", enumPickedOptionName);

  • This didn't work, always getting null from Type.GetType(enumTypeName); But I solved, see my answer. – Raphael Ribeiro Jun 27 '17 at 13:06
  • Did you use your enumeration's namespace in the call to the function? (e.g. - GetEnumValue("EnumNameSpace."+enumTypeName, enumPickedOptionName) –  Jun 27 '17 at 17:50
  • Yes, I did, maybe this isn't working coz the enum is in another project that is referenced in main project, I don't know. – Raphael Ribeiro Jun 27 '17 at 20:26
  • ah, yes...I thought that it was an enumeration local to your project. There are some other ways to do this outside of what has been presented, but it requires that you either know the enumeration type or use a known class property that is of the enumeration type. Let me know if you have any interest in the specifics (both use typeof(object) as a parameter instead of a string denoting the enum name). –  Jun 28 '17 at 03:51
0

I solved the problem this way:

private int GetEnumValue(string assemblyName, string enumTypeName, string enumPickedOptionName)
{
    int result = -1;

    Assembly assembly = Assembly.Load(assemblyName);
    Type enumType = assembly.GetTypes().Where(x => x.Name == 
    enumTypeName).FirstOrDefault();

    result = (int)Enum.Parse(enumType, enumPickedOptionName, true);

    return result;
}
Raphael Ribeiro
  • 529
  • 5
  • 18