Search code examples
c#enumssystem.reflection

How to get enum value having enum type name and enum option name


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){}

Solution

  • 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;
    }