C# dealing with invalid user input
- by Zka
Have a simple console app where user is asked for several values to input. Input is read via console.readline(). Ex
Name: Fred //string
Lastname: Ashcloud //string
Age: 28 //int
I would like to make sure that int and double types are entered and if the user enters garbage, lets him repeat the procedure.
Example, if the user enters "28 years old" where age expects int the app will crash. What is the best way to check for these inputs?
Right now I can only think of:
while (!Int32.TryParse(text, out number))
{
Console.WriteLine("Error write only numbers");
text = Console.ReadLine();
}
Is there any other way to do this? try catch statements if one wants to give a more detailed feedback to the user? How in that case?