Reputation: 960
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
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
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
Reputation: 2654
Check this instead
string result = Console.ReadLine();
And after check the result
Upvotes: 5
Reputation: 86848
KeyChar
is a char
while "Y"
is a string
.
You want something like KeyChar == 'Y'
instead.
Upvotes: 16