How to Make a CLI Menu in C#

Creating a Command Line Interface (CLI) menu in C# is not only straightforward but also an engaging way to improve your application’s user experience. CLI menus serve as the backbone of user interaction in various console-based applications, offering a streamlined pathway for users to access various functionalities with ease. By guiding users through a series of choices, a well-designed menu can significantly enhance the navigability and overall usability of your software, making it more intuitive and user-friendly.

Initializing the Application

Start by setting up the main loop that keeps the menu visible. This section initializes the application and defines the loop condition.

Console.WriteLine("Simple Menu Application");

bool showMenu = true;

while (showMenu)
{
    showMenu = MainMenu();
}

Defining the Main Menu

The MainMenu method is where the menu options are displayed, and user input is handled. This method clears the console, presents the options, and processes the user’s choice.

static bool MainMenu()
{
    Console.Clear();
    Console.WriteLine("What would you like to order?");
    Console.WriteLine("1) Pizza");
    Console.WriteLine("2) Taco");
    Console.WriteLine("3) Burger");
    Console.WriteLine("4) Exit");
    Console.Write("\nSelect an option: ");

Processing User Input

After displaying the menu options, use a switch statement to determine the action based on the user’s input. This segment demonstrates handling each menu choice and includes the logic for exiting the loop.

    switch (Console.ReadLine())
    {
        case "1":
            Console.WriteLine("You selected pizza!");
            PauseBeforeContinuing();
            return true;
        case "2":
            Console.WriteLine("You selected taco!");
            PauseBeforeContinuing();
            return true;
        case "3":
            Console.WriteLine("You selected burger!");
            PauseBeforeContinuing();
            return true;
        case "4":
            return false;
        default:
            Console.WriteLine("Invalid option. Please try again.");
            PauseBeforeContinuing();
            return true;
    }
} // End of MainMenu()

Pausing Between Actions

Finally, include a method that pauses the application, allowing users to see the outcome of their choice before the menu reappears.

static void PauseBeforeContinuing()
{
    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

Wrapping Up

I hope you enjoyed this short tutorial. A good menu will increase the UX of your application and make it more enjoyable to use.

Recent Posts

SOLID - Dependency Inversion Principle (DIP) in C#
SOLID - Interface Segregation Principle (ISP) in C#
SOLID - Liskov Substitution Principle (LSP) in C#
SOLID - Open/Closed Principle (OCP) in C#
SOLID - Single Responsiblity Principle (SRP) in C#
How to Make a CLI Menu in C#