Unfortunately, there isn't a non-generic overload of
TryParse
. Which means you'll need to use some reflection to invoke the method.
For example:
public static class EnumExtensions
{
public static bool TryParse(Type enumType, string value, bool ignoreCase, out Enum result)
{
if (enumType is null) throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum) throw new ArgumentException("Not an enum type.", nameof(enumType));
MethodInfo baseMethod = typeof(Enum).GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(m => m.Name == nameof(Enum.TryParse))
.First(m => m.GetParameters().Length == 3);
MethodInfo realMethod = baseMethod.MakeGenericMethod(enumType);
object[] parameters = new object[] { value, ignoreCase, null };
bool parsed = (bool)realMethod.Invoke(null, parameters);
result = parsed ? (Enum)parameters[2] : default;
return parsed;
}
public static bool TryParse(Type enumType, string value, out Enum result)
{
if (enumType is null) throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum) throw new ArgumentException("Not an enum type.", nameof(enumType));
MethodInfo baseMethod = typeof(Enum).GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(m => m.Name == nameof(Enum.TryParse))
.First(m => m.GetParameters().Length == 2);
MethodInfo realMethod = baseMethod.MakeGenericMethod(enumType);
object[] parameters = new object[] { value, null };
bool parsed = (bool)realMethod.Invoke(null, parameters);
result = parsed ? (Enum)parameters[1] : default;
return parsed;
}
}