First of all, interactive UI based on console-only application is a big overkill, to be practical. Nearly all practical, or good, console-only applications don't use interactive user input. Instead, they expect all input in one command line. If command line is too big, such option as the name of the file containing all required input is used.
But it this code is just the useful exercise, you can do it. First of all, hide the echo on
Console.ReadKey
:
using System;
ConsoleKeyInfo key = Console.ReadKey(true);
Please see:
http://msdn.microsoft.com/en-us/library/x3h8xffw%28v=vs.110%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.consolekeyinfo(v=vs.110).aspx[
^].
Now, the key is: don't hard-code keys and menu option texts, especially if you are going to re-use them: show to the user in a menu, and then show the user's selection. Here is what you can do: put all this information into a dictionary, which will give you the search with the complexity O(1). Here is how:
using MenuItemDictionary = System.Collections.Generic.Dictionary<char, string>;
MenuItemDictionary menuItemDictionary = new MenuItemDictionary();
menuItemDictionary.Add('1', "Please Enter Scores");
menuItemDictionary.Add('1', "...");
foreach(var pair in menuItemDictionary)
Console.WriteLine("{0}) {1}", pair.Key, pair.Value);
string message;
if (menuItemDictionary.TryGetValue(key.KeyChar, out message)) {
Console.WriteLine("You have chosen: {0}", message);
} else {
}
Please see:
http://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx[
^],
http://msdn.microsoft.com/en-us/library/5tbh8a42%28v=vs.110%29.aspx[
^].
Now, the message (text of the menu option) is not all. You also need some action. What to do? Instead of using string type, create a type which composes string and action, which could be a delegate instance, with the delegate type, say,
System.Action
. For example:
using MenuItemDictionary = System.Collections.Generic.Dictionary<char, MenuItem>;
class MenuItem {
internal MenuItem(string name, System.Action action) {
this.Name = name;
this.Action = action;
}
internal string Name { get; private set; }
internal System.Action { get; private set; }
}
And then, populate dictionary with keys, and
MenuItem
instances, each representing name and action. Show the names with keys as shown above. The the key is recognized, show the choice to the user and call the action both taken from the dictionary in its value element of the type
MenuItem
.
—SA