Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 730
developer__c Avatar asked Mar 02 '26 22:03

developer__c


2 Answers

Rather than using the Parse method use TryParse instead.

int age;

bool isValidInt = int.TryParse(Console.ReadLine(), out age);
like image 127
Jamie Dixon Avatar answered Mar 04 '26 12:03

Jamie Dixon


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

like image 36
Rob Avatar answered Mar 04 '26 14:03

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!