I'm writing a code where the user has to input if he wants a feature or not by pressing "y" or "n" or writting "yes" or "no", without checking for case-sensitivity (so it needs to work if the user writes yES or YeS).
Also, if the user writes anything invalid, it says that this option is invalid, and asks again for the user to select an option.
Here's an abstraction of it:
static bool FeatureIsOn { get; set;}
static void Main()
{
bool optionIsValid;
do //Loops around until the option is valid
{
Console.WriteLine();
Console.Write("Enable Feature? [Y/N]: ");
string optionString = Console.ReadLine();
switch(optionString)
{
default:
Console.WriteLine("Invalid option.");
optionIsValid = false;
break;
case "Yes":
case "yes":
case "Y":
case "y":
FeatureIsOn = true;
optionIsValid = true;
break;
case "No":
case "no":
case "N":
case "n":
FeatureIsOn = false;
optionIsValid = true;
break;
}
} while (optionIsValid != true);
}
It's not very efficient to have a case for each possible way to write "yes". Is there a better way to do it?
Convert the string you want to check to uppercase or lowercase before checking:
static bool FeatureIsOn { get; set;}
static void Main()
{
bool optionIsValid;
do //Loops around until the option is valid
{
Console.WriteLine();
Console.Write("Enable Feature? [Y/N]: ");
string optionString = Console.ReadLine();
// convert string to uppercase
optionString = optionString.ToUpper();
switch(optionString)
{
case "YES":
case "Y":
FeatureIsOn = true;
optionIsValid = true;
break;
case "NO":
case "N":
FeatureIsOn = false;
optionIsValid = true;
break;
default:
Console.WriteLine("Invalid option.");
optionIsValid = false;
break;
}
} while (optionIsValid != true);
}