Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
tripbrock Avatar asked Oct 28 '11 15:10

tripbrock


1 Answers

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

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

like image 73
Gabe Avatar answered Oct 19 '22 03:10

Gabe