I’m trying to build generic function that get from user string and try to parse it to Enum valuse like this:
private Enum getEnumStringEnumType(Type i_EnumType)
{
string userInputString = string.Empty;
Enum resultInputType;
bool enumParseResult = false;
while (!enumParseResult)
{
userInputString = System.Console.ReadLine();
enumParseResult = Enum.TryParse(userInputString, true, out resultInputType);
}
}
But i get:
The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'System.Enum.TryParse<TEnum>(string, bool, out TEnum) .
The Error means that i need to decalare a specific Enum for resultInputType?
How can I fix this ?
Thanks.
The
TryParsemethod has the following signature:It has a generic type parameter
TEnumthat must be a struct and that is used to determine the type of enumeration being parsed. When you don’t provide it explicitly (as you did), it will take the type of whatever you provide as theresultargument, which in your case is of typeEnum(and not the type of the enumeration itself).Note that
Enumis a class (despite it inheriting fromValueType) and therefore it does not satisfy the requirement thatTEnumis a struct.You can solve this by removing the
Typeparameter and giving the method a generic type parameter with the same constraints (i.e.struct) as the generic type parameter on theTryParsefunction.So try this, where I’ve named the generic type parameter
TEnum:To call the method, use: