tripbrock
tripbrock

Reputation: 960

C# Console.Readkey - wait for specific input

I have a small C# console app I am writing.

I would like the app to wait for instruction from the user regarding either a Y or a N keypress (if any other key is pressed the app ignores this and waits for either a Y or a N and then runs code dependent on the Y or N answer.

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 its doesnt like the result.Keychat == as the operand cant be applied to a 'char' or 'string'

Any help please?

Thanks in advance.

Upvotes: 11

Views: 64541

Answers (4)

Corey
Corey

Reputation: 21

What you're looking for is something like this:

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();
    }
}

Upvotes: 2

ComeIn
ComeIn

Reputation: 1609

You probably want the user to confirm their response by pressing enter, so ReadLine is best. Also convert the string response to upper case for generic comparison check. Like so:

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

Upvotes: 0

GregM
GregM

Reputation: 2654

Check this instead

string result = Console.ReadLine();

And after check the result

Upvotes: 5

Gabe
Gabe

Reputation: 86848

KeyChar is a char while "Y" is a string.

You want something like KeyChar == 'Y' instead.

Upvotes: 16

Related Questions