I have the following generic unction which takes an Enum
type, displays a list of the 'options', then loops/waits for the user to select a viable option:
public static T AskGenericType<T>(string message) where T : Enum
{
//Display options
Console.WriteLine(message);
foreach (var item in Enum.GetValues(typeof(T)))
{
Console.WriteLine($"[{(int)item}] {item}");
}
var returnInt = TryParseInput();
while (true)
{
if (Enum.IsDefined(typeof(T), returnInt))
break;
//Cannot parse input as one of the choices presented from the Enum
Console.WriteLine($"Please choose from one of the options.");
returnInt = TryParseInput();
}
return (T)returnInt; //<---this produces the compile error
}
private static int TryParseInput()
{
int returnInt;
while (!int.TryParse(Console.ReadLine(), out returnInt))
{
//Cannot parse input as an integer
Console.WriteLine($"Selection is not a number. Please try again.");
}
return returnInt;
}
I can get the function to work if I remove the <T>
generics altogether from the function definition as well as inside the code block. The error I get is:
Cannot convert type 'int' to 'T'
I'm looking for suggestions on how I can preserve the generic nature of the function with the loop as I have several Enum
types to iterate through and I don't want to have to duplicate code for each one.
Update: I feel this is not a duplicate due to the nature in which I'm referencing the integer of the Enum
and the other referenced duplicates are not trying to parse an Enum
at all.