Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing String input into int in C#

Tags:

c#

How to convert the string input taken using Console.ReadLine() function in a C# code??? Suppose I have created 2 integer variables a and b. Now I want to take from user the values of a and b. How can this be performed in C#?

like image 828
Choudhury Saadmaan Mahmid Avatar asked May 08 '26 08:05

Choudhury Saadmaan Mahmid


2 Answers

Another option, that I usually use is int.TryParse

int retunedInt;
bool conversionSucceed = int.TryParse("your string", out retunedInt);

so it's good fit for fault tollerant pattern like:

if(!int.TryParse("your string", out retunedInt)) 
  throw new FormatException("Not well formatted string");
like image 131
Tigran Avatar answered May 09 '26 22:05

Tigran


You can use it with Int32.TryParse();

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

int i;
bool b = Int32.TryParse(yourstring, out i);
like image 38
Soner Gönül Avatar answered May 09 '26 21:05

Soner Gönül



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!