简体   繁体   中英

Validate user input C# (console)

I have the following code:

aVariable =  int.Parse(Console.ReadLine());

One problem I have is I cannot find any support material to help validate the user input, for instance if the user pressed the letter a, this would simply kill the program.

What can I do? Where can I find a decent tutorial?

Rather than using the Parse method use TryParse instead.

int age;

bool isValidInt = int.TryParse(Console.ReadLine(), out age);

You can use TryParse for this.. just google for this method. Or you can catch for exceptions to prevent your program to crash

int.Parse throws a FormatException, when the string cannot be parsed. You can catch this exception and handle it, eg show an error message.

Another way is to use TryParse:

int number = 0;
bool result = Int32.TryParse(value, out number);
if (result)
{
   Console.WriteLine("Converted '{0}' to {1}.", value, number);         
}

Validating user input is no different in a console app than it is in a Winforms app. It's also very similar to validating user input in an ASP.NET app, except that you don't have the nice Validation controls.

If you're coming from an ASP.NET background look at how people use CustomValidators - pay attention to the code-behind and ignore the client-side validation.

Also, you can use RegularExpressions in a Console app just as easily as you can in an ASP.NET app.

Probably the reason validation isn't mentioned specifically to Console apps is that validation of input is validation of input. The methods are the same almost everywhere. The only difference with ASP.NET comparatively is the existence of custom controls that help do it for you.

Use Int32.TryParse instead and test for a successful cast.

Int32 val;
if (Int32.TryParse(userInput, out val))
{
  // val is now the user input as an integer
}
else
{
  // bad user input
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM