Code enclosed below. I am coding a menu where the user types a number to select a menu option. It also is enclosed in a while loop, so the user can repeat the menu over and over again. It works perfectly on the first loop thru, but on the second it gives "Input string was not in a correct format." at the Console.ReadLine()
static void Main(string[] args)
{
bool again = true;
while (again)
{
string yourName = "Someone";
Console.WriteLine("\t1: Basic Hello, World.\n" +
"\t2: Calculate demoninations for a given value of change.\n" +
"\t3: Calculate properties of shapes.\n" +
"Please Select an Option: ");
int option = int.Parse(Console.ReadLine());//errors out here.
switch (option)
{
}
Console.Write("Press y to back to the main menu. Press any other key to quit: ");
char againChoice = (char)Console.Read();
if (againChoice == 'y')
{ again = true; }
else
{ again = false; }
}
Console.Write("Hit Enter to end");
Console.Read();
}
int option = int.Parse(Console.ReadLine());
Focus on writing debuggable code:
string input = Console.ReadLine();
int option = int.Parse(input);
Now you can use the debugger, set a breakpoint on the Parse() statement. And you'll easily see why the Parse() method threw an exception. And yes, it does not like an empty string. Now you have a shot at finding the bug in your code, Console.Read() required you to press the Enter key to complete but only returns a single character. The Enter key is still unprocessed, you'll get it on the next read call. Kaboom.
Get ahead by using Console.ReadKey() instead. And use int.TryParse() so a simple typing mistake does not crash your program.