crmepham
crmepham

Reputation: 4740

How do I return string value if consoleKey.Escape hasn't been pressed?

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

Answers (2)

Habib
Habib

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

EventHorizon
EventHorizon

Reputation: 2986

You can use menuOption = option.KeyChar.ToString();

Upvotes: 3

Related Questions