How would I make a Yes/No prompt in Console using C#?
You can easily go overboard on these Console login scripts. Here's my contribution:
bool confirmed = false;
string Key;
do {
Console.Write("Please enter a login key: ");
Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
ConsoleKey response;
do
{
Console.Write("Are you sure you want to choose this as your login key? [y/n] ");
response = Console.ReadKey(false).Key; // true is intercept key (dont show), false is show
if (response != ConsoleKey.Enter)
Console.WriteLine();
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
confirmed = response == ConsoleKey.Y;
} while (!confirmed);
Console.WriteLine("You chose {0}!", Key);
Console.ReadLine();
Sample output:
Please enter a login key: potato
You entered, potato as your login key!
Are you sure you want to choose this as your login key? [y/n] a
Are you sure you want to choose this as your login key? [y/n] s
Are you sure you want to choose this as your login key? [y/n] l
Are you sure you want to choose this as your login key? [y/n] d
Are you sure you want to choose this as your login key? [y/n] k
Are you sure you want to choose this as your login key? [y/n] f
Are you sure you want to choose this as your login key? [y/n] d
Are you sure you want to choose this as your login key? [y/n] n
Please enter a login key: banana
You entered, banana as your login key!
Are you sure you want to choose this as your login key? [y/n] y
You chose banana!
I remake it like a utils class I hope it's gonna be usefull:
class UtilsConsole
{
public static bool Confirm(string title)
{
ConsoleKey response;
do
{
Console.Write($"{ title } [y/n] ");
response = Console.ReadKey(false).Key;
if (response != ConsoleKey.Enter)
{
Console.WriteLine();
}
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
return (response == ConsoleKey.Y);
}
}
Use Console.ReadKey();
Console.WriteLine("Press 'y' if you would like awesome!");
ConsoleKeyInfo cki = Console.ReadKey();
if (cki.Key.ToString() == "y")
{
//do what you need for yes
}else {
// presses something other then Y
}