developer__c
developer__c

Reputation: 636

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?

Upvotes: 2

Views: 5239

Answers (5)

David
David

Reputation: 73564

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.

Upvotes: 2

PVitt
PVitt

Reputation: 11760

int.Parse throws a FormatException, when the string cannot be parsed. You can catch this exception and handle it, e.g. 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);         
}

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101604

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
}

Upvotes: 1

Rob
Rob

Reputation: 4947

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

Upvotes: 3

Jamie Dixon
Jamie Dixon

Reputation: 54001

Rather than using the Parse method use TryParse instead.

int age;

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

Upvotes: 5

Related Questions