TryParse has the following signature:
ryParse<tenum>(string value, bool ignoreCase, out TEnum result)
where TEnum : struct, new()
</tenum>
It has a generic type parameter
TEnum
that must be a
struct
and that it uses to determine the type of
enum
that it is parsing. When you don't provide it explicitly (as you did), it will take the type of the resultInputType variable, which is Enum (and not the type of the enumeration itself). Note that
Enum
is a class (even tough it inherits from ValueType) and therefore it does not satisfy the requirement that
TEnum
is a
struct
.
You can solve this by giving the method a generic argument instead of a Type parameter. The generic type parameter
TEnum
must have the same constraints (i.e. struct) as the same parameter on the TryParse function. Otherwise you could put a class in the method while
TryParse
does not accept that.
So try this:
private static TEnum getEnumStringEnumType<tenum>()
where TEnum : struct
{
string userInputString = string.Empty;
TEnum resultInputType = default(TEnum);
bool enumParseResult = false;
while (!enumParseResult)
{
userInputString = System.Console.ReadLine();
enumParseResult = Enum.TryParse(userInputString, true, out resultInputType);
}
return resultInputType;
}
</tenum>
To call the method, use:
getEnumStringEnumType<myenum>();</myenum>