I am currently writing a C# console application. Part of it is, that the user needs to enter a fairly complex system name. To make it easier I wrote a function that uses a string[] keywords and auto completes the string the user is typing in - on the run (which makes it different to this post in my opinion)
The code is working and acts as expected, but I am curious how the code could be improved (e.g. usability, efficiency). Also, what functionalities are missing, which you'd expect?
Thank you for the feedback!
class Program
{
static void Main(string[] args)
{
string[] Keywords = new string[4] { "aX1223", "aE_334", "L_test1", "L_test2" };
if (Keywords.Length == 0)
throw new ArgumentException(nameof(Keywords), "No Keywords set!");
bool searching = true; // true while looking for the keyword
Console.CursorVisible = true; // To help users understand where they are typing
string userInput = ""; // Initialization of output
string suggestion = Keywords[0]; // Initialization of default suggestion
int toClear = suggestion.Length; // Get the length of the line that needs to be cleared
while (searching)
{
Console.Write(new String(' ', toClear)); // Clear line
Console.CursorLeft = 0; // Relocate cursor to line start
Console.Write(userInput); // Write what has been written previously
if (suggestion != "") // If there is a suggestion fitting the entered string,
{ // complete the string in color and reset the cursor
int col = Console.CursorLeft;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write(suggestion.Substring(userInput.Length));
Console.ForegroundColor = ConsoleColor.White;
Console.CursorLeft = col;
}
string tempInput = Console.ReadKey().KeyChar.ToString();
if (tempInput.Equals("\r")) // Evaluate input:
{ // -> Enter
if (!suggestion.Equals("")) // Valid entry?
{
searching = false;
userInput = suggestion; // -> use suggestion
}
}
else if (tempInput.Equals("\b")) // Deleting last sign
{
if (userInput.Length > 0)
userInput = userInput.Substring(0, userInput.Length - 1);
}
else // Any other sign is added to the string
userInput += tempInput;
// Set length to clear, if suggestion == "", the system string length needs to be cleared
toClear = (userInput.Length > suggestion.Length) ? userInput.Length : suggestion.Length;
// Reset suggestion. If no match is found, suggestion remains empty
suggestion = "";
// Check keywords for suggestion
for (int i = 0; i < Keywords.Length; i++)
{
if (Keywords[i].StartsWith(userInput))
{
suggestion = Keywords[i];
break;
}
}
}
// reset cursor visibility
Console.CursorVisible = false;
}
}