I wrote small console application where you can choose an item from given list of strings. Works fine so far but since I am beginner I have some questions if I am doing this right. My biggest concerns are if I should use fields here or properties, if I am using the static keyword correctly, if I should use the fields in the methods directly (like I am doing it now) or I should pass them as parameters. In future this class I want to use in multiple places so it makes sense to be static I think. If you have suggestions on some other parts also please comment.
ConsoleSelectMenu.cs:
namespace ConsoleApp
{
class ConsoleSelectMenu
{
static int selectedLineIndex = 0;
static ConsoleKey pressedKey;
static bool readyToSelectUp = true;
static bool readyToSelectDown = true;
static bool haveWeStarted = false;
public static string DrawSelectMenu(SelectMenuOptions options)
{
Console.WriteLine(options.Question);
do
{
UpdateMenu(options.Choices);
pressedKey = Console.ReadKey().Key;
Console.Write("\b \b");
readyToSelectUp = pressedKey == ConsoleKey.DownArrow && selectedLineIndex + 1 < options.Choices.Count;
readyToSelectDown = pressedKey == ConsoleKey.UpArrow && selectedLineIndex - 1 >= 0;
if (readyToSelectUp) selectedLineIndex++;
else if (readyToSelectDown) selectedLineIndex--;
} while (pressedKey != ConsoleKey.Enter);
return options.Choices[selectedLineIndex];
}
private static void UpdateMenu(List<string> list)
{
if (!readyToSelectUp && !readyToSelectDown) return;
if (haveWeStarted) ClearList(list);
foreach (var item in list)
{
bool isSelected = item == list[selectedLineIndex];
Console.WriteLine($"{(isSelected ? "> " : " ")}{item}");
}
haveWeStarted = true;
}
private static void ClearList(List<string> list)
{
for (int i = 0; i < list.Count; i++)
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop - (i + 1));
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, currentLineCursor);
}
Console.SetCursorPosition(0, Console.CursorTop - list.Count);
}
}
public class SelectMenuOptions
{
public string Question { get; set; }
public List<string> Choices { get; set; }
}
}
Programs.cs
var options = new SelectMenuOptions
{
Question = "Please choose an option",
Choices = new List<string>() { "Opt_1", "Opt_2", "Opt_3" }
};
var result = ConsoleSelectMenu.DrawSelectMenu(options);
Console.WriteLine(result);