C # Console.Readkey - wait for specific input

I have a small C # console application that I am writing.

I want the application to wait for instructions from the user regarding pressing the Y or N key (if any other key is pressed, the application ignores this and expects either Y or N, and then runs a code depending on the Y or N Answers.

I came up with this idea,

while (true)
{
    ConsoleKeyInfo result = Console.ReadKey();
    if ((result.KeyChar == "Y") || (result.KeyChar == "y"))
    {
         Console.WriteLine("I'll now do stuff.");
         break;
    }
    else if ((result.KeyChar == "N") || (result.KeyChar == "n"))
    {
        Console.WriteLine("I wont do anything");
        break;
    }
}

Sadly though, VS says he doesn't like the result. Keychat == since the operand can not apply to 'char' or 'string'

Any help please?

Thanks in advance.

+5
source share
4 answers

KeyCharis char, and "Y"is string.

- KeyChar == 'Y'.

+8

string result = Console.ReadLine();

+2

, -

       void PlayAgain()
    {
        Console.WriteLine("Would you like to play again? Y/N: ");
        string result = Console.ReadLine();
        if (result.Equals("y", StringComparison.OrdinalIgnoreCase) || result.Equals("yes", StringComparison.OrdinalIgnoreCase))
        {
            Start();
        }
        else
        {
            Console.WriteLine("Thank you for playing.");
            Console.ReadKey();
        }
    }
+2
source

You probably want the user to confirm their answer by pressing enter, so it is best to use ReadLine. Also convert the string response to uppercase for a general comparison check. For instance:

string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
    // Do what ya do ...
0
source

All Articles