Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance of unknown Enum with string value using reflection in C#

I have a problem working out how exactly to create an instance of an enum when at runtime i have the System.Type of the enum and have checked that the BaseType is System.Enum, my value is an int value matching an item in the mystery Enum.

The code i have so far is just the logic described above as shown below.

        if (Type.GetType(type) != null)
        {
            if (Type.GetType(type).BaseType.ToString() == "System.Enum")
            {
                return ???;
            }
        }

When working with Enums in the past i have always know at code time which enum i am trying to parse but in this scenario im confused and have had little luck articulating my question in a google friendly way... I would usually do something like

(SomeEnumType)int

but since i dont know the EnumType at code time how can i achieve the same thing?

like image 753
Jarmez De La Rocha Avatar asked Apr 06 '13 20:04

Jarmez De La Rocha


2 Answers

Use the ToObject method on the Enum class:

var enumValue = Enum.ToObject(type, value);

Or like the code you provided:

if (Type.GetType(type) != null)
{
    var enumType = Type.GetType(type);
    if (enumType.IsEnum)
    {
        return Enum.ToObject(enumType, value);
    }
}
like image 139
Dan Avatar answered Oct 24 '22 00:10

Dan


Use (ENUMName)Enum.Parse(typeof(ENUMName), integerValue.ToString())

as a generic function (edited to correct syntax errors)...

    public static E GetEnumValue<E>(Type enumType, int value) 
                        where E : struct
    {
        if (!(enumType.IsEnum)) throw new ArgumentException("Not an Enum");
        if (typeof(E) != enumType)
            throw new ArgumentException(
                $"Type {enumType} is not an {typeof(E)}");
        return (E)Enum.Parse(enumType, value.ToString());
    }

old wrong version:

public E GetEnumValue(Type enumType, int value) where E: struct
{
  if(!(enumType.IsEnum)) throw ArgumentException("Not an Enum");
  if (!(typeof(E) is enumType)) 
       throw ArgumentException(string.format(
           "Type {0} is not an {1}", enumType, typeof(E));
  return Enum.Parse(enumType, value.ToString());
}
like image 35
Charles Bretana Avatar answered Oct 24 '22 00:10

Charles Bretana