Reputation: 43
I know this might be a simple question but how can I add validation to this switch statement. I want that if the user inputs a different number than 1,2 or 3 an error message will be displayed.
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine(" 1. Create Account ");
Console.WriteLine(" 2. Login ");
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
string userChoice = Console.ReadLine();
switch (userChoice)
{
case "1":
Console.Clear();
cl_class.CreateAccount();
DisplayMenu();
Console.ReadKey();
break;
case "2":
Console.Clear();
Login();
DisplayMenu();
Console.ReadKey();
break;
}
Upvotes: 0
Views: 286
Reputation: 4826
You want the default
keyword.
Use it after your last case
(order doesn't technically matter, per the documentation at the link below, but you'd have a hard time convincing me to not put it last - it's just common practice).
switch (userChoice)
{
case "1":
Console.Clear();
cl_class.CreateAccount();
DisplayMenu();
Console.ReadKey();
break;
case "2":
Console.Clear();
Login();
DisplayMenu();
Console.ReadKey();
break;
default:
//Display error stuff
}
I left out a case
for 3, since you did not include one in your example. If you want default to not catch "3", obviously just add that as a new case
above the default.
More info here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch#the-default-case
Upvotes: 6