Introduction
The focus of this article is to provide an easy-to-use menu system for C# console projects.
NuGet package Spectre.Console is required to construct the menu using Actions to execute items in the menu.
Benefits of using a menu
A developer can easily test different operations, whether to learn something new, quickly try out code slated for a project, or provide options for a dotnet tool.
Also, many online classes are organized into chapters/sections. Consider breaking them up into menu items.
Base parts
A class which is responsible for displaying menu items and what code to execute using an Action with or without parameters.
public class MenuItem
{
public int Id { get; set; }
public required string Text { get; set; }
public required Action Action { get; set; }
public override string ToString() => Text;
}
A class that builds the menu using the class above, and another class that has methods to execute when a menu item is selected.
In the sample projects provided
- The MenuOperations class is responsible for building the menu
- The Operations class contains methods to execute using an Action
from the menu selection
- Each method has code to display the method name along with code to stop execution, which, when pressing ENTER, returns to the menu.
Entry point
A while statement is used to present a menu, with one menu option to exit the application.
Example 1 uses an Action with no parameters
internal partial class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Clear();
var menuItem = AnsiConsole.Prompt(MenuOperations.SelectionPrompt());
menuItem.Action();
}
}
}
Example 2 uses an Action with a parameter whose menuItem.Id property references a primary key in a database table; the operation, in this case, saves an image to disk.
internal partial class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Clear();
var menuItem = AnsiConsole.Prompt(MenuOperations.SelectionPrompt());
menuItem.Action(menuItem.Id);
}
}
}
dotnet tool example to read column descriptions for tables in a database.
Implmentation
Using one of the provided sample projects, create a new console project.
- Add NuGet package Spectre.Console to the project
- Add folders,
ModelsandClasses - Add MenuItem under the Models folder
- Add an empty MenuOperations class under the Classes folder
- Add code provided from one of Main methods to display the menu
- Export the project as a new project template for a starter project
Tips
- When something is unclear, set breakpoints and examine the code in the local window
- Consider writing code in class projects that are executed from the Operations class, as in this class project, Customer record used here.



Top comments (0)