Text-based Menu Class for Console Applications
This class helps in creating and using menus in console applications by using delegates. It will show you the basics of array lists and delegates.
Introduction
This is my very first article and it will probably contain mistakes and the language will not be perfect, but I will keep it updated and I will edit it until it gets good, so, I need your feedback.
Almost every console-based program written in C# will make use of Console.ReadLine()
to read in data. Mostly, the programmer will use a if
-else
statement to handle the data input, especially when inputting choices from menus. This interesting class will teach you the basics of collections and delegates while providing a good framework for a more powerful menu class.
The Menu Class and its Interface
The menu class is very simple to use; just instantiate it and use the Add
method to add new options to menu, and finally, use the Show
method to print it and let it handle the user's choice.
Here is how it works: each menu option is a MenuItem
class. It is nothing but an object containing the option's descriptions and a delegate
, an object that points to a function, that will be called when and if the option is chosen. This delegate will point to a function that will handle the choice.
The MenuItem
s are stored in an ArrayList
, a very useful collection class. A collection class is self-explanatory: it holds a collection of objects, often providing search, remove and object manipulation functionalities. The ArrayList
is pretty simple; the name Array
comes from that fact that it can be transformed into an Array
of any type, and I will use it because the Menu
class does not need the power of a Hashtable
collection or a Dictionary
collection, more enhanced collection classes. ArrayList
is just fine for us.
Creating and Showing a Menu
Firstly, write the functions that will handle the user's choice and the delegates. You will see how simple that is. Our Menu
class uses the MenuCallback
delegate, which returns nothing and has no parameters. Whenever you use a delegate, you need to:
- Create a new delegate type and
- Use the
new
keyword to store a new delegate.
private static MenuCallback mcOption1 = new MenuCallback(Option1);
private static MenuCallback mcOption2 = new MenuCallback(Option2);
private static void Option1()
{
Console.WriteLine("Option 1 chosen.");
}
private static void Option2()
{
Console.WriteLine("Option 2 chosen.");
}
Secondly, create a new Menu
instance and add the delegates and options to it. Then, show it. This is simple, too.
Menu m = new Menu();
m.Add("Option 1", mcOption1);
m.Add("Option 2", mcOption2);
m.Show();
Now, it is over. The Menu
class will handle the user's input and call the desired function using the delegate you've created. The sample will show everything better.