C# dealing with invalid user input

Posted by Zka on Stack Overflow See other posts from Stack Overflow or by Zka
Published on 2010-04-25T15:04:18Z Indexed on 2010/04/25 15:13 UTC
Read the original article Hit count: 259

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about userinput