C# Console.Readkey - wait for specific input
58,236
Solution 1
KeyChar
is a char
while "Y"
is a string
.
You want something like KeyChar == 'Y'
instead.
Solution 2
Check this instead
string result = Console.ReadLine();
And after check the result
Solution 3
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();
}
}
Author by
tripbrock
Updated on October 05, 2021Comments
-
tripbrock over 2 years
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.
-
tripbrock over 12 yearsThank you so much. A schoolboy error on my part. Still struggling with C# after the php move! Thanks again.
-
Carol over 9 yearsAn alternative would be this:
result.Key == ConsoleKey.Y
-
Gabe over 9 years@K_Rol: That might work. I'd be concerned that it would accept not just
Y
andShift+Y
, but alsoCtrl+Y
. -
Carol over 9 yearsYou are right, I just tested it and it does accept Shift+Y (or any combination).