Reputation: 4740
I have a basic console application. Users can select from a numbered menu, 1-5. If they press ESC the program closes but if they don't press ESC a switch
is used to determine which option they chose by which string they input (1, 2, 3, 4 or 5).
This code isn't working:
static string mainMenu()
{
string menuOption;
// get user input
ConsoleKeyInfo option = Console.ReadKey();
if (option.Key == ConsoleKey.Escape)
{
Environment.Exit(0);
}
return menuOption = Console.ReadLine();
}
How can I get the string value of what the user input in to menuOption
whilst also checking if the user pressed ESC
?
Upvotes: 0
Views: 1011
Reputation: 223207
If your options are only single character, then its better if you return a character instead of string and then have the switch statement on character. Your method can be like:
static char mainMenu()
{
ConsoleKeyInfo option = Console.ReadKey();
if (option.Key == ConsoleKey.Escape)
{
Environment.Exit(0);
}
return option.KeyChar;
}
and then you can use it in switch statement like:
char option = mainMenu();
switch (option)
{
case '1':
//...........
}
Or use the method directly in switch statement like:
switch (mainMenu())
Upvotes: 1