Im using Console.ReadKey() to choose from a number of options that varies from time to time. Before this initial code snippet there is a for loop that counts occurances into counter variable of type int.
The point is to use Console.ReadKey() to get an int.
int choice = ReadKey();
Console.WriteLine("");
if (choice < counter)
{
mail.to = result[counter-1].email;
}
By using the following methods
static int ReadKey()
{
ConsoleKeyInfo choice = Console.ReadKey();
char convertedchoice = choice.KeyChar;
string convertedchoice2 = convertedchoice.ToString();
int result = TryInt(convertedchoice2);
return result;
}
static int TryInt(string totry)
{
while (true)
{
int result;
if (int.TryParse(totry, out result))
{
return result;
}
Console.WriteLine("Sorry, you need to enter a number. Try again.");
}
}
I tried using ToString() but this was the way that it would let me do it in the end. So this looks kind of inneffective to me and hence I would really appreciate some guidance as what to do differently?
Edit:
I ended up with a combination of all the good answers below. Thanks alot guys.
static int ReadKey()
{
while (true)
{
ConsoleKeyInfo choice = Console.ReadKey();
if (char.IsDigit(choice.KeyChar))
{
int answer = Convert.ToInt32(choice.KeyChar);
return answer - 48; //-48 because 0 is represented in unicode by 48 and 1 by 49 etc etc
}
Console.WriteLine("\nSorry, you need to input a number");
}
}