1
public static T ParseEnum<T>(string value)
        {
            return (T) Enum.Parse(typeof (T), value, true);
        }

I can simply do:

var parsed = EnumUtils.ParseFromString<Gender>("Man");

but sometimes I get type of enum as string. Can i Convert string to enum type and use it in my EnumUtils.

I trid like:

Type enumType = Type.GetType(Gender,true);
Object o = (Activator.CreateInstance(enumType)); 

var parsed = EnumUtils.ParseFromString<enumType>("Man");

but not working. enumType is not recognozed in generic way.

I also know for this site: Converting a string to a class name and How do I use reflection to call a generic method?

but does not help me, because I don't know the type of Enum it is not always Gender, can be 100 other enums. I know the name of enum as string and not as type.

Community
  • 1
  • 1
senzacionale
  • 20,448
  • 67
  • 204
  • 316

2 Answers2

2

No you can't use a generic method like that. You have have to have the generic type at compile time.

There's no need for you to call the your EnumUtils.ParseFromString() method. Just call Enum.Parse() directly.

String typeNameString;
 ...
Type enumType = Type.GetType(typeNameString,true);
Object parsed =  Enum.Parse(enumType, value, true)
shf301
  • 31,086
  • 2
  • 52
  • 86
1

The most generic way I can think of would be to return an Enum type from your parse method:

enum MyEnum
{
    Value1
}

Type enumType = typeof(MyEnum);
string enumString = "Value1";
Enum enumValue = enumString.ToEnum(enumType);

additionaly you can turn your parse method into an extension:

public static Enum ToEnum(this string value, Type enumType)
{
    return (Enum)Enum.Parse(enumType, value, true);
}
t3chb0t
  • 16,340
  • 13
  • 78
  • 118