Successfully added
.NET
by Roman
Prompting User for valid Input in Console Application
In a console apps, there is often a need to obtain user input from the console while ensuring that the input is not empty or only whitespace characters.
In this sample, we define a method GetUserInput
that takes an optional message parameter. It continuously prompts the user until a non-empty, non-whitespace input is provided.
static string GetUserInput(string message = "Please enter some input:")
{
string input;
do
{
Console.WriteLine(message);
input = Console.ReadLine()?.Trim();
} while (string.IsNullOrWhiteSpace(input));
return input;
}
Explanation:
message
parameter allows customizing input prompt message.Console.ReadLine()?.Trim()
reads user input and trims leading/trailing whitespace.- The
?.
operator is used for null-conditional access, ensuring thatConsole.ReadLine()
doesn't throw a null reference exception if the input is null. do-while
loop ensures user input is not empty or whitespace.
Referenced in:
Comments