Unless the is a good reason to avoid using TryParse, I agree with @P a u l
Here is an alternate for working with int
values only.
The following language extension keep code clean although you can take the code in the extension body and use directly in a loop.
internal static class StringExtensions
{
public static bool IsInteger(this string sender)
=> !string.IsNullOrEmpty(sender) && sender.All(char.IsDigit);
}
Test the extension
while (true)
{
Console.Write("Enter value ");
string userInput = Console.ReadLine();
if (userInput.IsInteger())
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(Convert.ToInt32(userInput));
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"'{userInput}' is not valid");
}
Console.ResetColor();
ConsoleKeyInfo ch;
Console.Write("Press the Escape (Esc) key to quit");
ch = Console.ReadKey();
if (ch.Key == ConsoleKey.Escape)
{
Environment.Exit(0);
}
Console.Clear();
}