dimanche 2 décembre 2018

How to compact identical repeating Else If statements

I am experimenting with simple programs that the User can navigate with basic ReadLine input. At any given time during an input, there are a couple of commands that are always accessible regardless of the circumstances, here is an example:

else if(input.ToLower() == "exit" || input.ToLower() == "leave")
{
    Console.Clear();
    ExitProgram.ExitProg();
    calcInput = false;
}
else if(input.ToLower() == "back" || input.ToLower() == "menu")
{
    TxtFun.CTxt("Returning to previous menu.");
    Console.ReadLine();
    Console.Clear();
    calcInput = false;
    calcLoop = false;
}
else
{
    TxtFun.CTxt("Invalid input.");
    Console.ReadLine();
    Console.Clear();

    calcInput = false;
}

Above are 2 If Else statements that are repeated EVERY time I ask for User Input and then check it. This gets very line heavy as I nest User Input several times.

My question is, would there be a way to compact these repeating Else If statements into a function or a separate class, in order to save time and (a lot) of space, that would be efficient to insert into an If/Else If branch?

((Bonus Points if there would be a way to contain the ever repeated "Else" at the end that returns "Invalid Input", but that is not the main question or goal.))

Aucun commentaire:

Enregistrer un commentaire